java HTTP服务器客户端示例

时间:2016-07-22 08:34:27

标签: java apache http httpclient httpserver

我从这个链接获得一个http服务器:http://www.rgagnon.com/javadetails/java-have-a-simple-http-server.html(第一个例子)

我把它运行得很好。然后我使用以下小代码作为客户端与服务器通信:

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

我执行了它但是我得到了这个例外:

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)

有什么想法可以解决这个问题吗?

3 个答案:

答案 0 :(得分:1)

您的apache服务器是否在80上运行?

当您附加服务器的源代码时,您的服务器似乎在8000端口上运行,因此尝试使用此端口与您的服务器通信。

http://127.0.0.1:8000/info

答案 1 :(得分:1)

在您给定的链接中,我可以看到服务器正在端口8000上运行。

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

示例本身解释了如何连接。    编译并执行。要访问本地服务器,请打开浏览器

 http://localhost:8000/test. 

答案 2 :(得分:0)

您需要URL的协议。例如:

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

假设它在端口80上运行。如果它在另一个端口上运行,那么也包括端口。例如:

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