【发布时间】:2013-05-27 11:43:38
【问题描述】:
我在访问安静的 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,所以看起来“应用程序/json”是正确的值。他也做 --data-binary,我假设 streamWriter 为我做。
有谁知道是什么导致了这个错误?
【问题讨论】: