Java如何执行HTTP Get请求?

下面是一个使用HttpClient库通过Http Get请求检索网站内容的示例。我们从创建DefaultHttpClient类的实例开始。然后,我们通过创建HttpGet类的实例来定义Http get请求,并指定要检索的网站的网址。

要执行请求,我们调用HttpClient.execute()方法并传递HttpGet作为参数。该执行返回一个HttpResponse对象。从该响应对象中,我们可以通过访问getEntity().getContent()来读取网站的内容,这将使我们InputStream对该内容有所了解。

有关更多详细信息,请看下面的代码片段:

package org.nhooo.example.httpclient;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class HttpGetExample {
    public static void main(String[] args) {
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet("https://kodejava.org");

        try {
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                try (InputStream stream = entity.getContent()) {
                    BufferedReader reader =
                            new BufferedReader(new InputStreamReader(stream));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        System.out.println(line);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Maven依赖

<!-- https://search.maven.org/remotecontent?filepath=org/apache/httpcomponents/httpclient/4.5.9/httpclient-4.5.9.jar -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.9</version>
</dependency>

Maven中央