带有ContentType Multipart / form-data的WebException

时间:2016-01-17 21:10:30

标签: c# json httpwebrequest multipartform-data

我正在尝试创建一个httpwebrequest,以便与客户的api连接。这适用于大多数api,但其中一个需要ContentType =" multipart / form-data",这就是为什么我必须将它添加到我的请求中。但是因为我添加了它,我在使用GetResponse方法的行处获得了System.Net.WebException。我的JsonRequest是正确的,因为我在一个演示网站上试过它,但我不知道如何处理这个例外!如果我不在ContentType multipart / form-data,我从api得到一个错误消息,"并非所有参数都设置正确"。 我希望你能帮助我!

 var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "text/json";
        httpWebRequest.Method = requestMethode;
        httpWebRequest.Accept = "application/json";
            httpWebRequest.ContentType = "multipart/form-data";
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Close();
        }
        string strResponse = "";
        try
        {
            using (WebResponse httpResponse = httpWebRequest.GetResponse()) // error here
            {
                using (Stream responseStream = httpResponse.GetResponseStream())
                {
                    using (StreamReader streamReader = new StreamReader(responseStream))
                    {
                        strResponse = streamReader.ReadToEnd();
                    }
                }
            }
        }
        catch (WebException exception)
        {
            throw exception;
        }
        JObject jobject = JObject.Parse(strResponse);
        return jobject;
    }

很多!

1 个答案:

答案 0 :(得分:2)

您尝试调用的远程端点看起来需要multipart/form-data编码请求。我强烈建议您阅读corresponding specification以更好地熟悉需要通过网络发送的确切有效负载。这样您就可以更好地了解代码的问题所在。

一旦你阅读了规范,就可以得到以下内容:

string json = "PUT THE SAMPLE JSON TAKEN FROM HERE https://i.materialise.com/api/docs/cart-item-creation-api/";
var url = "https://imatsandbox.materialise.net/web-api/cartitems/register";
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", NumberFormatInfo.InvariantInfo);
request.ContentType = "multipart/form-data; boundary=" + boundary;
boundary = "--" + boundary;

using (var stream = request.GetRequestStream())
using (var writer = new StreamWriter(stream))
{
    writer.WriteLine(boundary);
    writer.WriteLine("Content-Disposition: form-data; name=\"data\"; filename=\"blob\"");
    writer.WriteLine("Content-Type: application/json");
    writer.WriteLine();
    writer.Write(json);
    writer.WriteLine();
    writer.WriteLine(boundary + "--");
}

using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
    string strResponse = reader.ReadToEnd();
    return JObject.Parse(strResponse);
}

另请注意,我已删除了您只是重新抛出的无意义try/catch