在.NET中POST多部分/混合

问题描述 投票:1回答:1

正如标题所说,如果它以任何方式帮助我有这个java代码(multipart由json对象和文件组成):

// 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);

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

到目前为止,我设法像这样POST 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();
}

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

java c# .net multipart
1个回答
4
投票

我终于设法做到这样:

        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;
© www.soinside.com 2019 - 2024. All rights reserved.