HttpWebRequest PATCH方法和JSON给出错误请求

本文关键字:出错 错误 请求 JSON PATCH 方法 HttpWebRequest | 更新日期: 2023-09-27 18:16:13

我正在尝试发送一些数据到REST API。API的文档告诉我必须使用PATCH,并以JSON的形式提供数据。API也需要oAuth 2.0来进行调用,所以我首先获取一个访问令牌,并将其附加到API url调用。

我有以下代码:

public MyResponse HttpPatch(
        string url,
        string content,
        Dictionary<string, string> headers,
        string contentType = "application/json")
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        var request = (HttpWebRequest)WebRequest.Create(Uri.EscapeUriString(url));
        if (request == null)
            throw new ApplicationException(string.Format("Could not create the httprequest from the url:{0}", url));
        request.Method = "PATCH";
        foreach (var item in headers)
            request.Headers.Add(item.Key, item.Value);
        UTF8Encoding encoding = new UTF8Encoding();
        var byteArray = Encoding.ASCII.GetBytes(content);
        request.ContentLength = byteArray.Length;
        request.ContentType = contentType;
        Stream dataStream = request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();
        try
        {
            var response = (HttpWebResponse)request.GetResponse();
            return new MyResponse(response);
        }
        catch (WebException ex)
        {
            HttpWebResponse errorResponse = (HttpWebResponse)ex.Response;
            return new MyResponse(errorResponse);
        }
    }

在try块中,我在. getresponse上得到一个错误,它说"(400)Bad Request"。我提供给方法的值:

url = https://api.myserver.com/v1/users/1234?access_token=my_access_token(myserver和my_access_token在我的代码中有实际值)

content = lang=国籍=fr& country= fr& first_name=John&last_name=Doe

headers = dictionary with 1 element: {"Authorization", "ApiKey myuser:mykey"}(myuser和mykey在我的代码中有实际值)

contentType = "application/json"

是否有什么明显的,我错过了,可以解释"错误的请求"错误?这个错误可能的原因是什么?

我使用的访问令牌是正确的,端点URL是正确的。我不确定方法的"PATCH"值,我可以这样做吗?因为MSDN文档没有在可能的值中提到这一点:https://msdn.microsoft.com/nl-be/library/system.net.httpwebrequest.method (v = vs.110) . aspx

拉着我的头发,挣扎了2天现在让电话工作,所以希望有人能给我一些好的指示,给我一些好的指示,把我放在正确的轨道上?

HttpWebRequest PATCH方法和JSON给出错误请求

最终成功了。原来我的内容类型是错误的,因为我没有提供json。将其更改为"application/x-www-form-urlencoded"并保留method的PATCH值后,它现在可以工作了。

相关文章: