我是 JSON 新手,正在使用 VS 2013/C#。这是请求和响应的代码。很简单,不是吗?
Request request = new Request();
//request.hosts = ListOfURLs();
request.hosts = "www.cnn.com/www.cisco.com/www.microsoft.com/";
request.callback = "process";
request.key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string output = JsonConvert.SerializeObject(request);
//string test = "hosts=www.cnn.com/www.cisco.com/www.microsoft.com/&callback=process&key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
try
{
var httpWebRequest = (HttpWebRequest) WebRequest.Create("http://api.mywot.com/0.4/public_link_json2?);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = output;
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
}
}
catch (WebException e)
{
MessageBox.Show(e.ToString());
}
//response = true.
//no response = false
return true;
}
当我运行它时,我得到一个 405 错误指示方法不允许。
在我看来,这里至少存在两个可能的问题:(1) WoT API (www.mywot.com/wiki/API) 需要一个带有正文的 GET 请求,而 httpWebRequest 不允许在httpWebRequest.Method; 或 (2) 序列化字符串未正确序列化。
注意:在下面我不得不删除前导的“http://”,因为我没有足够的代表来发布超过 2 个链接。
它应该看起来像:api.mywot.com/0.4/public_link_json2?hosts=www.cnn.com/www.cisco.com/www.microsoft.com/&callback=process&key=xxxxxxxxxxxxxx
但看起来像:api.mywot.com/0.4/public_link_json2?{"hosts":"www.cnn.com/www.cisco.com/www.microsoft.com/","callback":"process","键":"xxxxxxxxxxxxxxxxxx"}。
如果我浏览到:api.mywot.com/0.4/public_link_json2?hosts=www.cnn.com/www.cisco.com/www.microsoft.com/&callback=process&key=xxxxxxxxxxxxxx; 我得到了预期的回应。
如果我浏览到:api.mywot.com/0.4/public_link_json2?{"hosts":"www.cnn.com/www.cisco.com/www.microsoft.com/","callback":"process","键":"xxxxxxxxxxxxxxxxxx"}; 我收到 403 denied 错误。
如果我硬编码请求并作为 GET 发送,如下所示:
var httpWebRequest = (HttpWebRequest) WebRequest.Create("api.mywot.com/0.4/public_link_json2? + "test"); 它也按预期工作。
我将不胜感激任何帮助,希望我已经把问题弄清楚了。谢谢。