Question

I am trying to make a simple GET request for a website, but I am getting unknown host exception.

Given below is my code--

     DefaultHttpClient client = new DefaultHttpClient();
     HttpHost targetHost=null;
     targetHost= new HttpHost("google.com/", 80, "http");
     HttpGet httpget = new HttpGet("about-us.html");
     BasicHttpContext localcontext = new BasicHttpContext();
     try {
        HttpResponse response = client.execute(targetHost, httpget, localcontext);
Was it helpful?

Solution

It looks like you have a simple problem here.

The URL for your 'HttpHost' object is malformed. You need to drop the '/' from "google.com/". It should work after that. I used your code with that single modification & it worked.

DefaultHttpClient client = new DefaultHttpClient();
HttpHost targetHost = new HttpHost("google.com", 80, "http"); 
HttpGet httpget = new HttpGet("about-us.html");
BasicHttpContext localContext = new BasicHttpContext();
HttpResponse response = null;

try { response = client.execute(targetHost, httpget, localContext); 
      System.out.println(response.getStatusLine()
}
catch(Exception e){
    // Enter error-handling code here.
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top