【问题标题】:POST multipart/mixed in .NET在 .NET 中发布多部分/混合
【发布时间】:2014-07-14 15:24:42
【问题描述】:

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

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

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

【问题讨论】:

  • 你有什么问题?
  • 我想知道如何像我发布的 JAVA 代码一样在 .NET(最好是 C#)中创建和发布 multipart/mixed。
  • 我看到我的问题已经被否决了,我想知道为什么。如果有问题或不清楚,请告诉我。
  • 可能是因为您的问题表明自己没有努力解决问题。现在就像“我用 java 编码的。有人可以为我用 C# 编码吗?”。您应该发布到目前为止您尝试过的内容,并告诉我们哪些内容不起作用、预期的行为是什么以及发生了什么。
  • @BackSlash,我认为在 .NET 中创建和发布多部分会很容易,我只是错过了。无论如何,我确实付出了很多努力来寻找解决方案,所以我编辑了我的问题。如果还有什么不清楚的地方,请随时询问。

标签: java c# .net multipart


【解决方案1】:

我终于做到了:

        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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 2016-11-08
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多