Skip to main content
 首页 » 编程设计

java之.NET 中的 POST 多部分/混合

2024年02月06日28pander-it

正如标题所说,如果它有任何帮助,我有这个 java 代码(多部分由 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#) 中创建相同的内容

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

但是我想把文件一起发。内容类型必须是“multipart/mixed”,因为这是 Web 服务获得的内容。我试图找到一些支持 multiparts 的包,但除了这个 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;