我在访问一个安静的 Web 服务时遇到了一些代码问题。运行此代码,它在 var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); 处出错 并且返回的异常是:“System.Net.WebException:远程服务器返回错误:(415)不支持的媒体类型。”
public bool CreateAccount(string myUsername, string url, string authtoken) {
try {
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.MediaType="application/json";
httpWebRequest.Accept="application/json";
httpWebRequest.Method = "POST";
WebHeaderCollection headers = new WebHeaderCollection();
headers.Add("Authorization: Token"+authtoken);
httpWebRequest.Headers = headers;
using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) {
streamWriter.Write("{username : '"+myUsername+"'}");
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); // Fails on this line.
using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) {
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
string json = streamReader.ReadToEnd();
}
return true;
} catch (WebException e) {
throw e;
return false;
}
//return true;
}
我已经为 ContentType、MediaType 和 Accept 尝试了各种方法,但是服务开发人员给我的工作示例提供了 -H "Content-Type: application/json" to curl,所以看起来 "application/ json”是正确的值。他也做 --data-binary,我认为 streamWriter 为我做的。
有谁知道可能导致此错误的原因?