java中HttpClient使用方法举例详解
作者:一口酥Hac
概要
Java 11引入了HttpClient
作为一个新的API,用于在Java应用程序中进行HTTP通信
。HttpClient
提供了发送HTTP请求和接收HTTP响应的功能,并且相比于依赖第三方库如Apache HttpClient或OkHttp,它提供了一种简单、一致且更加集成的方式来处理HTTP通信。作为Java的一部分,HttpClient
被设计成与Java平台更好地集成,使得开发者能够更轻松地处理HTTP请求和响应,同时减少了对外部库的依赖。
HttpClient
的主要类包括:java.net.http.HttpClient
:HttpClient是用于发送HTTP请求和处理HTTP响应的主要类。它提供了一种简单且一致的方式来执行HTTP操作,包括同步和异步的请求发送、连接池管理、请求和响应的拦截器等功能。
java.net.http.HttpRequest
:HttpRequest是用于表示HTTP请求的类。通过HttpRequest对象,您可以设置请求的URL、请求方法、请求头、请求体等信息,并构建一个完整的HTTP请求对象,用于发送给服务器。
java.net.http.HttpResponse
:HttpResponse是用于表示HTTP响应的类。当客户端发送HTTP请求后,服务器会返回一个HTTP响应,HttpResponse对象用于表示这个响应。通过HttpResponse对象,您可以获取响应的状态码、响应头、响应体等信息,以便进一步处理响应。
但是,如果你在使用Java 11之前的版本,并且想要使用类似的功能,你可能需要引入第三方库的依赖,如Apache HttpClient。以下是使用Apache HttpClient的一个示例依赖项:
<!-- Apache HttpClient依赖 --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency>
JDK11 及之后的版本 举例
第一种以下是一个简单的例子,演示如何使用HttpClient发送GET请求:
public static void main(String[] args) throws Exception { // 创建一个HttpClient实例 HttpClient httpClient = HttpClient.newHttpClient(); // 创建一个HTTP请求 指定URI HttpRequest httpRequest = HttpRequest.newBuilder() .uri(URI.create("https://api.uomg.com/api/rand.qinghua")) // 使用 URI 创建请求 .build(); // 发送 HTTP 请求并获取响应 HttpResponse<String> response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()); // 输出响应的状态码和响应体 System.out.println("响应状态码:" + response.statusCode()); System.out.println("响应体:" + response.body()); }
第二种以下是一个示例,演示如何使用sendAsync()方法发送异步GET请求:
public static void main(String[] args) { HttpClient httpClient = HttpClient.newHttpClient(); HttpRequest httpRequest = HttpRequest.newBuilder() .uri(URI.create("https://api.uomg.com/api/rand.qinghua")) .build(); CompletableFuture<HttpResponse<String>> future = httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString()); future.thenAccept(response -> { System.out.println("响应状态码:" + response.statusCode()); System.out.println("响应体:" + response.body()); }).join();// 等待异步操作完成 }
第三种:
以下是一个使用HttpClient发送POST请求的示例代码:
public static void main(String[] args) throws Exception { // 创建一个 HttpClient 实例 HttpClient client = HttpClient.newHttpClient(); // 构建请求体参数 Map<String, String> requestBody = new HashMap<>(); requestBody.put("param1", "value1"); requestBody.put("param2", "value2"); // 构建 POST 请求 HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.uomg.com/api/rand.qinghua")) .header("Content-Type", "application/json") // 设置请求头 .POST(buildRequestBody(requestBody)) // 设置请求体 .build(); // 发送请求并获取响应 HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); // 输出响应码和响应体 System.out.println("Response Code: " + response.statusCode()); System.out.println("Response Body: " + response.body()); } // 构建请求体 // buildRequestBody方法的作用是将一个Map<String, String>类型的数据转换为符合JSON格式的字符串 // 转换后:{"param1":"value1","param2":"value2"} private static HttpRequest.BodyPublisher buildRequestBody(Map<String, String> data) { StringBuilder builder = new StringBuilder(); builder.append("{"); for (Map.Entry<String, String> entry : data.entrySet()) { builder.append("\"").append(entry.getKey()).append("\":\"").append(entry.getValue()).append("\","); } builder.deleteCharAt(builder.length() - 1); // 删除最后一个逗号 builder.append("}"); return HttpRequest.BodyPublishers.ofString(builder.toString()); }
JDK11 之前的版本 举例
第一步引入依赖:
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.14</version> </dependency>
第二步封装一个工具类:
public class HttpClientUtil { static final int TIMEOUT_MSEC = 5 * 1000; /** * 发送GET方式请求 */ public static String doGet(String url, Map<String, String> paramMap) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); String result = ""; CloseableHttpResponse response = null; try { URIBuilder builder = new URIBuilder(url); if (paramMap != null) { for (String key : paramMap.keySet()) { builder.addParameter(key, paramMap.get(key)); } } URI uri = builder.build(); //创建GET请求 HttpGet httpGet = new HttpGet(uri); //发送请求 response = httpClient.execute(httpGet); //判断响应状态 if (response.getStatusLine().getStatusCode() == 200) { result = EntityUtils.toString(response.getEntity(), "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return result; } /** * 发送POST方式请求,参数为键值对形式 */ public static String doPost(String url, Map<String, String> paramMap) throws IOException { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建参数列表 if (paramMap != null) { List<NameValuePair> paramList = new ArrayList(); for (Map.Entry<String, String> param : paramMap.entrySet()) { paramList.add(new BasicNameValuePair(param.getKey(), param.getValue())); } // 模拟表单 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); httpPost.setEntity(entity); } // 设置请求配置 httpPost.setConfig(builderRequestConfig()); // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (Exception e) { throw e; } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } /** * 发送POST方式请求,参数为JSON格式 */ public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); if (paramMap != null) { //构造json格式数据 JSONObject jsonObject = new JSONObject(); for (Map.Entry<String, String> param : paramMap.entrySet()) { jsonObject.put(param.getKey(), param.getValue()); } StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8"); //设置请求编码 entity.setContentEncoding("utf-8"); //设置数据类型 entity.setContentType("application/json"); httpPost.setEntity(entity); } // 设置请求配置 httpPost.setConfig(builderRequestConfig()); // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } /** * 构建请求配置 */ private static RequestConfig builderRequestConfig() { return RequestConfig.custom() .setConnectTimeout(TIMEOUT_MSEC) // 设置连接超时时间 .setConnectionRequestTimeout(TIMEOUT_MSEC) // 设置从连接池获取连接的超时时间 .setSocketTimeout(TIMEOUT_MSEC) // 设置请求获取数据的超时时间 .build(); } }
第三步使用这个工具类:(简单例子测试一下)
public static void main(String[] args) { String s = HttpClientUtil.doGet("https://api.uomg.com/api/rand.qinghua", null); System.out.println(s); }
使用JDK11添加如下依赖
<!--JDK11缺少的依赖--> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-core</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency>
小结
总的来说,HttpClient是一个功能强大、灵活易用的HTTP客户端库,适用于各种Java应用程序,如Web应用、后台服务等,能够帮助开发者轻松实现HTTP通信功能。
到此这篇关于java中HttpClient使用方法的文章就介绍到这了,更多相关java中HttpClient使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!