在这篇快速文章中,我们将逐步讨论如何使用Apache HttpClient 4.5
来进行Http GET请求。HTTP GET方法表示指定资源的代表。这可以是简单的获得一个HTML页面,或获得JSON、XML或等格式的资源。使用HTTP GET请求方法的请求应该是Idempotent的,也就是说:这些请求应该只检索数据,不应该有其他效果。HttpClient
支持HTTP/1.1规范中定义的所有HTTP方法:GET
、HEAD
、POST
、PUT
、DELETE
、TRACE
和OPTIONS
。每个方法类型都有一个特定的类:HttpGet
、HttpHead
、HttpPost
、HttpPut
、HttpDelete
、HttpTrace
和HttpOptions
。
在这个例子中,我们将使用HttpGet
类来处理GET HTTP方法。查看Apache HttpClient POST HTTP请求实例
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请求。
CloseableHttpClient httpclient = HttpClients.createDefault()
HttpClients.createDefault()
方法以默认配置创建CloseableHttpClient
实例。
HttpGet httpget = new HttpGet("http://httpbin.org/get");
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);
int status = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
在下面的例子中,我们从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"}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2018/10/apache-httpclient-get-http-request-example.html
内容来源于网络,如有侵权,请联系作者删除!