我試圖發送一些數據到REST API。 API的文檔告訴我必須使用PATCH,並將數據提供爲JSON。該API還需要oAuth 2.0來進行調用,所以我首先獲取訪問令牌並將其附加到api url調用。HttpWebRequest PATCH方法和JSON給出了錯誤的請求
我有以下代碼:
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塊,我得到.GetResonse,它說的錯誤 「(400)錯誤的請求」。 值我提供的方法:
URL = https://api.myserver.com/v1/users/1234?access_token=my_access_token (MYSERVER和my_access_token在我的代碼實際值)
含量= LANG = FR &國籍= FR &國家= FR & FIRST_NAME =約翰&姓氏= Doe的
頭=字典用1個元素:{ 「授權」, 「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天,現在拿到的呼叫工作,所以希望有人能告訴我給我一些好的指針的光放我在正確的軌道上?