POST multipart/mixed in .NET
本文关键字:in NET mixed multipart POST | 更新日期: 2023-09-27 18:12:54
正如标题所说,如果它有任何帮助,我有这个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服务得到的。我试图找到一些支持多部件的包,但我发现除了这个http://www.example-code.com/csharp/mime_multipartMixed.asp(这不是免费的,所以我不能使用它)。
我终于做到了:
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;