在HttpResponse execute for android中,主机名可能不为null

caf*_*anu 10 android httpresponse http-post illegalargumentexception

我收到错误"目标主机不能为空,或在参数中设置".

  • I DO具有Internet权限在我的清单文件
  • 我把"http://"放在我的网址之前
  • 我会对 URL进行编码

这是我的代码:

   String url = "http://maps.google.com/maps/api/directions/json?origin=1600 Pennsylvania Avenue NW, Washington, DC 20500&destination=1029 Vermont Ave NW, Washington, DC 20005&sensor=false";
   HttpClient httpclient = new DefaultHttpClient();
   String goodURL = convertURL(url);//change weird characters for %etc
   HttpPost httppost = new HttpPost(goodURL);
   HttpResponse response = httpclient.execute(httppost);
Run Code Online (Sandbox Code Playgroud)

在第5行(上面的最后一行),我的程序抛出异常.这是确切的错误:

java.lang.IllegalArgumentException: Host name may not be null
Run Code Online (Sandbox Code Playgroud)

我在方法convertURL中编码我的字符串...

goodURL = http://maps.google.com/maps/api/directions/json?origin=3%20Cedar%20Ave%2c%20Highland%20Park%2c%20NJ%2008904&destination=604%20Bartholomew%20Road%2c%20Piscataway%2c%20New%20Jersey%2008854&sensor=false

有什么建议?谢谢!

Dev*_*red 5

我不确定你的URL编码方法在做什么,但是如果你正在使用框架中的方法URLEncoder,你应该永远不要传递完整的URL,只需要编码的参数列表来转义特殊字符.

对完整URL进行编码将百分比转义每个字符,包括://into %3A%2F%2F和所有其他斜杠%2F.

goodUrl编码后,请查看字符串的值.

  • "NetworkOnMainThreadException"正是它所说的.Android不允许您从主线程进行网络访问,因为它会阻止UI; 您必须为网络I/O创建后台线程.您可以从以下培训文章中了解更多信息:http://developer.android.com/training/basics/network-ops/index.html (2认同)