我收到错误“目标主机不能为空,或在参数中设置”。
这是我的代码:
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中编码我的字符串...
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
有什么建议吗? 谢谢!
答案 0 :(得分:5)
我不确定您的网址编码方法在做什么,但是如果您使用的是URLEncoder
框架中的方法,则永远不会传递完整的网址,只是您需要编码的参数列表以转义特殊字符。
对完整网址进行编码会将每个字符的百分比转义,包括://
转换为%3A%2F%2F
以及所有其他斜杠转换为%2F
。
编码后,请查看goodUrl
字符串的值。
答案 1 :(得分:1)
只需使用:
URLEncoder.encode(YOUR_STRING);
答案 2 :(得分: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);