Apache HttpClient GET HTTP请求示例

x33g5p2x  于2022-10-07 转载在 Apache  
字(8.0k)|赞(0)|评价(0)|浏览(399)

在这篇快速文章中,我们将逐步讨论如何使用Apache HttpClient 4.5来进行Http GET请求。HTTP GET方法表示指定资源的代表。这可以是简单的获得一个HTML页面,或获得JSON、XML或等格式的资源。使用HTTP GET请求方法的请求应该是Idempotent的,也就是说:这些请求应该只检索数据,不应该有其他效果。
HttpClient支持HTTP/1.1规范中定义的所有HTTP方法:GETHEADPOSTPUTDELETETRACEOPTIONS。每个方法类型都有一个特定的类:HttpGetHttpHeadHttpPostHttpPutHttpDeleteHttpTraceHttpOptions

在这个例子中,我们将使用HttpGet类来处理GET HTTP方法。查看Apache HttpClient POST HTTP请求实例

使用Apache HttpClient - 添加依赖

Apache HttpClient库允许处理HTTP请求。要使用这个库,请在你的Maven或Gradle构建文件中添加一个依赖项。你可以在这里找到最新版本:https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient

我们使用maven来管理我们的依赖,并使用Apache HttpClient 4.5版。在你的项目中添加以下依赖,以便进行HTTP POST请求方式。

<dependency>
 <groupId>org.apache.httpcomponents</groupId>
 <artifactId>httpclient</artifactId>
 <version>4.5</version>
</dependency>

开发步骤

让我们创建一个逐步的例子,使用HttpClient做一个HTTP GET请求。

1. 使用辅助类HttpClients创建CloseableHttpClient的实例。

CloseableHttpClient httpclient = HttpClients.createDefault()

HttpClients.createDefault()方法以默认配置创建CloseableHttpClient实例。

2. 创建一个基本的GET请求

HttpGet httpget = new HttpGet("http://httpbin.org/get");

3. 创建一个自定义的响应处理程序

ResponseHandler < String > responseHandler = response - > {
    int status = response.getStatusLine().getStatusCode();
    if (status >= 200 && status < 300) {
        HttpEntity entity = response.getEntity();
        return entity != null ? EntityUtils.toString(entity) : null;
    } else {
        throw new ClientProtocolException("Unexpected response status: " + status);
    }
};

4. 通过execute()方法发送基本的GET请求

String responseBody = httpclient.execute(httpget, responseHandler);

5. 获取HTTP响应的状态代码

int status = response.getStatusLine().getStatusCode();

6. 获取一个响应实体

HttpEntity entity = response.getEntity();

HttpClient HTTP GET请求方法实例

在下面的例子中,我们从http://httpbin.org/get检索一个资源。这个资源返回一个JSON对象,我们将简单地打印到控制台。在这个例子中,我们使用Java 7 try-with-resources来自动处理ClosableHttpClient的关闭,我们也使用Java 8 lambdas来处理ResponseHandler

package com.javadevelopersguide.httpclient.examples;

import org.apache.http.HttpEntity;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;

/**
* This example demonstrates the use of {@link HttpGet} request method.
* @author Ramesh Fadatare
*/
public class HttpGetRequestMethodExample {

    public static void main(String...args) throws IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

            //HTTP GET method
            HttpGet httpget = new HttpGet("http://httpbin.org/get");
            System.out.println("Executing request " + httpget.getRequestLine());

            // Create a custom response handler
            ResponseHandler < String > responseHandler = response - > {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            };
            String responseBody = httpclient.execute(httpget, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        }
    }
}

输出:

Executing request GET http://httpbin.org/get HTTP/1.1
----------------------------------------
{
  "args": {}, 
  "headers": {
    "Accept-Encoding": "gzip,deflate", 
    "Connection": "close", 
    "Host": "httpbin.org", 
    "User-Agent": "Apache-HttpClient/4.5 (Java/1.8.0_172)"
  }, 
  "origin": "49.35.12.218", 
  "url": "http://httpbin.org/get"
}

更多的例子

让我们来讨论如何在实时项目中使用HttpClient。考虑到我们已经部署了Spring boot Restful CRUD APIs。请看这篇文章 - Spring Boot 2 + hibernate 5 + CRUD REST API教程。

让我们写一个Rest客户端,从以下Rest服务中获取JSON

package com.javadevelopersguide.httpclient.examples;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
* This example demonstrates the use of {@link HttpGet} request method.
* @author Ramesh Fadatare
*/
public class HttpGetRequestMethodExample {

    public static void main(String[] args) throws IOException {
        getUsers();
        getUserById();
    }

    private static void getUsers() throws ClientProtocolException, IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

            //HTTP GET method
            HttpGet httpget = new HttpGet("http://localhost:8080/api/v1/users");
            System.out.println("Executing request " + httpget.getRequestLine());

            // Create a custom response handler
            ResponseHandler < String > responseHandler = response - > {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            };
            String responseBody = httpclient.execute(httpget, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        }
    }

    private static void getUserById() throws IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

            //HTTP GET method
            HttpGet httpget = new HttpGet("http://localhost:8080/api/v1/users/5");
            System.out.println("Executing request " + httpget.getRequestLine());

            // Create a custom response handler
            ResponseHandler < String > responseHandler = response - > {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            };
            String responseBody = httpclient.execute(httpget, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        }
    }
}

输出

Executing request GET http://localhost:8080/api/v1/users HTTP/1.1
----------------------------------------
[{"id":5,"firstName":"Ram","lastName":"Jadhav","emailId":"ramesh123@gmail.com","createdAt":"2018-09-11T11:19:56.000+0000",
"createdBy":"Ramesh","updatedAt":"2018-09-11T11:26:31.000+0000","updatedby":"Ramesh"},
{"id":6,"firstName":"Ramesh","lastName":"fadatare","emailId":"ramesh@gmail.com","createdAt":"2018-09-11T11:20:07.000+0000",
"createdBy":"Ramesh","updatedAt":"2018-09-11T11:20:07.000+0000","updatedby":"Ramesh"},
{"id":17,"firstName":"John","lastName":"Cena","emailId":"john@gmail.com","createdAt":"2018-09-19T08:28:10.000+0000",
"createdBy":"Ramesh","updatedAt":"2018-09-19T08:28:10.000+0000","updatedby":"Ramesh"},
{"id":18,"firstName":"John","lastName":"Cena","emailId":"john@gmail.com","createdAt":"2018-09-19T08:29:29.000+0000",
"createdBy":"Ramesh","updatedAt":"2018-09-19T08:29:29.000+0000","updatedby":"Ramesh"}]
Executing request GET http://localhost:8080/api/v1/users/5 HTTP/1.1
----------------------------------------
{"id":5,"firstName":"Ram","lastName":"Jadhav","emailId":"ramesh123@gmail.com","createdAt":"2018-09-11T11:19:56.000+0000",
"createdBy":"Ramesh","updatedAt":"2018-09-11T11:26:31.000+0000","updatedby":"Ramesh"}

相关文章