在 .NET 中 POST 多部分/混合

The*_* K. 2 .net c# java multipart

正如标题所说,如果它有任何帮助,我有这个java代码(多部分由json objectfile 组成):

// Construct a MultiPart
MultiPart multiPart = new MultiPart();

multiPart.bodyPart(new BodyPart(inParams, MediaType.APPLICATION_JSON_TYPE));
multiPart.bodyPart(new BodyPart(fileToUpload, MediaType.APPLICATION_OCTET_STREAM_TYPE));

// POST the request
final ClientResponse clientResp = resource.type("multipart/mixed").post(ClientResponse.class, multiPart);
Run Code Online (Sandbox Code Playgroud)

(使用 com.sun.jersey.multipart ),我想在 .NET (C#) 中创建相同的

到目前为止,我设法像这样发布 json 对象:

Uri myUri = new Uri("http://srezWebServices/rest/ws0/test");
var httpWebRequest = (HttpWebRequest)WebRequest.Create(myUri);
httpWebRequest.Proxy = null;
httpWebRequest.Accept = "application/json";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
Console.Write("START!");

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())){
                string json = new JavaScriptSerializer().Serialize(new
                {
                    wsId = "0",
                    accessId = "101",
                    accessCode = "x@ds!2"
                });

                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();

                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
}
Run Code Online (Sandbox Code Playgroud)

但我想把文件一起发送。内容类型必须是“multipart/mixed”,因为这是 Web 服务所获得的。我试图找到一些支持多部分的包,但除了这个http://www.example-code.com/csharp/mime_multipartMixed.asp(它不是免费的,所以我不能使用它)之外我什么也没找到。

The*_* K. 7

我终于设法这样做了:

        HttpContent stringStreamContent = new StringContent(json);
        stringStreamContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        HttpContent fileStreamContent = new StreamContent(fileStream);
        fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

        // Construct a MultiPart
        // 1st : JSON Object with IN parameters
        // 2nd : Octet Stream with file to upload
        var content = new MultipartContent("mixed");
        content.Add(stringStreamContent);
        content.Add(fileStreamContent);

        // POST the request as "multipart/mixed"
        var result = client.PostAsync(myUrl, content).Result;
Run Code Online (Sandbox Code Playgroud)