I am having the problems with a bit of code that accesses a RESTful Web service. Running This code, it errors out at var HttpResponse = (HttpWebResponse) httpwebrequest.getresponse (); And the exception returned is: "System.Net.WebException:The remote server returned an error: (415) Unsupported MEDIA TYP E. "
Public BOOLCreateAccount (stringMyUserName,stringUrlstringAuthtoken) { Try{HttpWebRequest HttpWebRequest=(HttpWebRequest) webrequest.create (URL); Httpwebrequest.contenttype="Application/json"; Httpwebrequest.mediatype="Application/json"; Httpwebrequest.accept="Application/json"; Httpwebrequest.method="POST"; WebHeaderCollection Headers=Newwebheadercollection (); Headers. ADD ("Authorization:token"+Authtoken); Httpwebrequest.headers=headers; using(StreamWriter StreamWriter =NewStreamWriter (Httpwebrequest.getrequeststream ())) {StreamWriter.Write ("{username: '"+myusername+"'}"); } varHttpResponse = (HttpWebResponse) httpwebrequest.getresponse ();//fails on the line. using(varStreamReader =NewStreamReader (Httpresponse.getresponsestream ())) {JavaScriptSerializer Jsserializer=NewJavaScriptSerializer (); stringJSON =Streamreader.readtoend (); } return true; } Catch(WebException e) {Throwe; return false; } //return true;}
I have tried various things for the ContentType, mediatype, and Accept, but the working example given to me by the develop Er of the service supplies-h "Content-type:application/json" to curl, so it would seem that ' Application/json ' is the CO Rrect value. He also does--data-binary, which I assume StreamWriter does for me.
Does anyone know what might is causing this error?
Figured it out.
When I do:
New webheadercollection (); Headers. ADD (""+Authtoken); = headers;
I accidentally blow away all of the existing headers this were created by doing:
" Application/json " ; Httpwebrequest.mediatype="application/json"; Httpwebrequest.accept="application/json"; " POST ";
The answer is to move the code where I create the header with the Auth token above the code where I set the other headers.
Source