带有 ContentType Multipart/form-data 的 WebException

WebException with ContentType Multipart/form-data

我正在尝试创建一个 httpweb 请求,以连接 api 位客户。这适用于大多数 api,但其中一个需要 ContentType = "multipart/form-data",这就是我必须将其添加到我的请求中的原因。但是自从我添加它后,我在使用 GetResponse 方法的那一行得到了一个 System.Net.WebException。我的 JsonRequest 是正确的,因为我在演示站点上尝试过,但我不知道如何处理这个异常!如果我不在 ContentType multipart/form-data,我会收到来自 api 的错误消息,即 "not all parameters are set correctly"。 希望你能帮帮我!

 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;
    }

非常感谢!

您尝试调用的远程端点似乎需要 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