-2

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?

Kallel Omar
  • 1,208
  • 2
  • 17
  • 51

3 Answers3

1

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

  • thank you for the answer it seems that 's fixed I got as displayed message: http response = HTTP/1.1 200 OK [Content-length: 30, Date: Fri, 22 Jul 2016 08:45:13 GMT] do you have an idea how I can the message sent by the server from response? – Kallel Omar Jul 22 '16 at 08:47
  • I used ResponseHandler to get the message sent by the server. Thank you again for the answer. – Kallel Omar Jul 22 '16 at 09:22
1

In your given link i can see server is running on port 8000.

new InetSocketAddress(8000)
String url = "http://127.0.0.1:8000/test"

Example itself explaining how to connect. Compile and execute. To access the local server, open a browser at

 http://localhost:8000/test. 
shivam
  • 511
  • 3
  • 13
0

You need the protocol for the URL. For example:

String url = "http://127.0.0.1/info";

Assuming it is running on port 80. If it is running on another port, then include the port too. For example:

String url = "http://127.0.0.1:8080/info";
stepanian
  • 11,373
  • 8
  • 43
  • 63