Search code examples
javaapachehttphttpclienthttpserver

java HTTP server client example


I get a http server from this link: http://www.rgagnon.com/javadetails/java-have-a-simple-http-server.html (the first example)

I run it an it's fine working. Then I used the following small code as a client to communicate with the server:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

public class Main {
    public static void main(String argv[]) throws ClientProtocolException, IOException
    {
        String url = "127.0.0.1/test";

        HttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(url);


        HttpResponse response = client.execute(request);
        System.out.println("http response = "+response.toString());
    }
}

I executed it but I got this exception:

Exception in thread "main" java.lang.IllegalStateException: Target host is null
    at org.apache.http.util.Asserts.notNull(Asserts.java:46)
    at org.apache.http.impl.client.InternalHttpClient.determineRoute(InternalHttpClient.java:125)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57)
    at httpClient.Main.main(Main.java:20)

is there an idea how I can fix this problem?


Solution

  • Is your apache server running on 80?

    As you attached the source code of server it seems your server running on 8000 port so try to communicate with your server using this port.

    http://127.0.0.1:8000/info