Reputation: 41
I'm trying to send some data to a REST API. The documentation of the API tells me that I have to use PATCH, and provide the data as JSON. The API also requires oAuth 2.0 to make the call, so I fetch an access token first and append that to the api url call.
I have the following code:
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);
}
}
In the try block, I get an error on .GetResonse, which says "(400) Bad Request". The values I provide to the method:
url = https://api.myserver.com/v1/users/1234?access_token=my_access_token (myserver and my_access_token have real values in my code)
content = lang=fr&nationality=FR&country=FR&first_name=John&last_name=Doe
headers = dictionary with 1 element: {"Authorization", "ApiKey myuser:mykey"} (myuser and mykey have real values in my code)
contentType = "application/json"
Is there anything obvious that I'm missing that could explain the "bad request" error? What could be possible reasons for this error?
The access token I use is correct, the endpoint URL is correct. I'm not sure about the "PATCH" value for method, can I do it like that? Because the MSDN documentation does not mention this in the possible values: https://msdn.microsoft.com/nl-be/library/system.net.httpwebrequest.method(v=vs.110).aspx
Pulling my hair and struggling for 2 days now to get the call working, so hopefully someone can show me the light of give me some good pointers to put me on the right track?
Upvotes: 3
Views: 7034
Reputation: 41
Got it working in the end. Turned out my content type was wrong, since I was not providing json. After changing it to "application/x-www-form-urlencoded" and keeping the PATCH value for method, it works now.
Upvotes: 1