10

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

  • 我的清单文件中确实有 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);

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

java.lang.IllegalArgumentException: Host name may not be null

我确实在方法 convertURL 中对我的字符串进行编码...

好网址=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

有什么建议么?谢谢!

4

3 回答 3

5

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

编码完整的 URL 将百分比转义每个字符,包括://into%3A%2F%2F和所有附加的斜杠 into %2F

goodUrl编码后查看字符串的值。

于 2012-09-21T20:48:41.150 回答
1

只需使用:

URLEncoder.encode(YOUR_STRING);
于 2012-09-21T20:19:48.870 回答
1

在发布请求之前对 URL 字符串进行编码,但仅对 ? 之后的参数进行编码:

String url = "http://maps.google.com/maps/api/directions/json?";
String params = "origin=1600 Pennsylvania Avenue NW, Washington, DC 20500&destination=1029 Vermont Ave NW, Washington, DC 20005&sensor=false";
HttpClient httpclient = new DefaultHttpClient();
String goodParams = convertURL(params);//change weird characters for %etc
HttpPost httppost = new HttpPost(url + goodParams);
HttpResponse response = httpclient.execute(httppost);
于 2012-09-21T20:33:16.190 回答