【转】get a mysterious problem,when i use HttpWebRequest in unity c# script

in script,i use HttpWebRequest to get service from network.but it comes a mysterious problem. the source code:

  1. string url = "http://apis.baidu.com/apistore/vop/baiduvopjson";
  2. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  3. print(request.Address);
  4. request.Method = "get";
  5. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  6. Stream s = response.GetResponseStream();
  7. StreamReader Reader = new StreamReader(s, Encoding.UTF8);
  8. string strValue = "";
  9. strValue = Reader.ReadToEnd();
  10. print (strValue);

the result is like(i have copy the html to a html file):alt text

but the mysterious problem comes.when i use this code in Visual studio c# project,here is the source code:

  1. string url = "http://apis.baidu.com/apistore/vop/baiduvopjson";
  2. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  3. request.Method = "get";
  4. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  5. Stream s = response.GetResponseStream();
  6. StreamReader Reader = new StreamReader(s, Encoding.UTF8);
  7. string strValue = "";
  8. strValue = Reader.ReadToEnd();
  9. Console.WriteLine(strValue);

the result which is true in fact is as follows:

  1. {"errNum":300202,"errMsg":"Missing apikey"}

do some one know what mistake do i make in unity project? why can i get the ture httpweb response?

1.jpg (21.9 kB)
 

1条回复

 · 添加您的回复
avatar image
1
 

个解答,截止elenzil 

the problem is not your use of HTTPWebRequest, the problem is your use of the remote service. if you use command-line "curl" with the same URL, you get the same response:

  1. curl http://apis.baidu.com/apistore/vop/baiduvopjson
  2. {"errNum":300202,"errMsg":"Missing apikey"}

or even just visit http://apis.baidu.com/apistore/vop/baiduvopjson in a browser - same response.

it seems like you should be providing an API key somehow. maybe as a form parameter, maybe as a URL parameter, header param, etc, etc. you should look up the docs for whatever service that is.

评论 ·  隐藏 1 · 分享
 

I have found the point of my problem....The string of request method should be uppercase....omg,the mono .net has such a slight difference with .net framework. Anyway,thanks for your reply.

posted on 2016-10-29 16:04  mimime  阅读(322)  评论(0编辑  收藏  举报