gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:30:07 25 4
gpt4 key购买 nike

正如标题所说,如果它有任何帮助,我有这个 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;

关于java - .NET 中的 POST 多部分/混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24740053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com