Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Host name may not be null in HttpResponse execute for android

I get the error "Target host must not be null, or set in parameters".

  • I DO have Internet permission in my manifest file
  • I have put 'http://' before my Url
  • I DO encode the URL

This is my code:

   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);

In 5th line (last line above), my program throws an exception. here is the exact error:

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

I Do encode my string in method 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

Any suggestions? Thanks!

like image 908
cafesanu Avatar asked Sep 21 '12 20:09

cafesanu


3 Answers

Just use:

URLEncoder.encode(YOUR_STRING);
like image 30
Samer Avatar answered Sep 24 '22 23:09

Samer


I'm not sure what your URL encode method is doing, but if you are using a method from the framework like URLEncoder, you should never pass the full URL, just the parameters list you need to encode to escape special characters.

Encoding the full URL will percent escape every character, including the :// into %3A%2F%2F and all additional slashes into %2F.

Take a look at the value of your goodUrl string after you encode it.

like image 147
devunwired Avatar answered Sep 24 '22 23:09

devunwired


Encode your URL string before you post the request, but only encode the parameters after the ?:

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);
like image 27
AWT Avatar answered Sep 22 '22 23:09

AWT