日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java开发小技巧(五):HttpClient工具类

發布時間:2025/4/9 java 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java开发小技巧(五):HttpClient工具类 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

前言

大多數Java應用程序都會通過HTTP協議來調用接口訪問各種網絡資源,JDK也提供了相應的HTTP工具包,但是使用起來不夠方便靈活,所以我們可以利用Apache的HttpClient來封裝一個具有訪問HTTP協議基本功能的高效工具類,為后續開發使用提供方便。

文章要點:

  • HttpClient使用流程
  • 工具類封裝
  • 使用實例

HttpClient使用流程

1、導入Maven依賴

<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.5</version> </dependency> <dependency><groupId>commons-codec</groupId><artifactId>commons-codec</artifactId><version>1.11</version> </dependency> <dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.8.5</version> </dependency>

2、創建HttpClient實例

HttpClient client = HttpClientBuilder.create().build();

3、創建請求方法的實例

GET請求使用HttpGet,POST請求使用HttpPost,并傳入請求的URL

// POST請求 HttpPost post = new HttpPost(url); // GET請求,URL中帶請求參數 HttpGet get = new HttpGet(url);

4、添加請求參數

普通形式

List<NameValuePair> list = new ArrayList<>(); list.add(new BasicNameValuePair("username", "admin")); list.add(new BasicNameValuePair("password", "123456"));// GET請求方式 // 由于GET請求的參數是拼裝在URL后方,所以需要構建一個完整的URL,再創建HttpGet實例 URIBuilder uriBuilder = new URIBuilder("http://www.baidu.com"); uriBuilder.setParameters(list); HttpGet get = new HttpGet(uriBuilder.build());// POST請求方式 post.setEntity(new UrlEncodedFormEntity(list, Charsets.UTF_8));

JSON形式

Map<String,String> map = new HashMap<>(); map.put("username", "admin"); map.put("password", "123456"); Gson gson = new Gson(); String json = gson.toJson(map, new TypeToken<Map<String, String>>() {}.getType()); post.setEntity(new StringEntity(json, Charsets.UTF_8)); post.addHeader("Content-Type", "application/json");

5、發送請求

調用HttpClient實例的execute方法發送請求,返回一個HttpResponse對象

HttpResponse response = client.execute(post);

6、獲取結果

String result = EntityUtils.toString(response.getEntity());

7、釋放連接

post.releaseConnection();

工具類封裝

HttpClient工具類代碼(根據相應使用場景進行封裝):

public class HttpClientUtil {// 發送GET請求public static String getRequest(String path, List<NameValuePair> parametersBody) throws RestApiException, URISyntaxException {URIBuilder uriBuilder = new URIBuilder(path);uriBuilder.setParameters(parametersBody);HttpGet get = new HttpGet(uriBuilder.build());HttpClient client = HttpClientBuilder.create().build();try {HttpResponse response = client.execute(get);int code = response.getStatusLine().getStatusCode();if (code >= 400)throw new RuntimeException((new StringBuilder()).append("Could not access protected resource. Server returned http code: ").append(code).toString());return EntityUtils.toString(response.getEntity());}catch (ClientProtocolException e) {throw new RestApiException("postRequest -- Client protocol exception!", e);}catch (IOException e) {throw new RestApiException("postRequest -- IO error!", e);}finally {get.releaseConnection();}}// 發送POST請求(普通表單形式)public static String postForm(String path, List<NameValuePair> parametersBody) throws RestApiException {HttpEntity entity = new UrlEncodedFormEntity(parametersBody, Charsets.UTF_8);return postRequest(path, "application/x-www-form-urlencoded", entity);}// 發送POST請求(JSON形式)public static String postJSON(String path, String json) throws RestApiException {StringEntity entity = new StringEntity(json, Charsets.UTF_8);return postRequest(path, "application/json", entity);}// 發送POST請求public static String postRequest(String path, String mediaType, HttpEntity entity) throws RestApiException {logger.debug("[postRequest] resourceUrl: {}", path);HttpPost post = new HttpPost(path);post.addHeader("Content-Type", mediaType);post.addHeader("Accept", "application/json");post.setEntity(entity);try {HttpClient client = HttpClientBuilder.create().build();HttpResponse response = client.execute(post);int code = response.getStatusLine().getStatusCode();if (code >= 400)throw new RestApiException(EntityUtils.toString(response.getEntity()));return EntityUtils.toString(response.getEntity());}catch (ClientProtocolException e) {throw new RestApiException("postRequest -- Client protocol exception!", e);}catch (IOException e) {throw new RestApiException("postRequest -- IO error!", e);}finally {post.releaseConnection();}} }

使用實例

GET請求

List<NameValuePair> parametersBody = new ArrayList(); parametersBody.add(new BasicNameValuePair("userId", "admin")); String result = HttpClientUtil.getRequest("http://www.test.com/user",parametersBody);

POST請求

List<NameValuePair> parametersBody = new ArrayList(); parametersBody.add(new BasicNameValuePair("username", "admin")); parametersBody.add(new BasicNameValuePair("password", "123456")); String result = HttpClientUtil.postForm("http://www.test.com/login",parametersBody);

POST請求(JSON形式)

Map<String,String> map = new HashMap<>(); map.put("username", "admin"); map.put("password", "123456"); Gson gson = new Gson(); String json = gson.toJson(map, new TypeToken<Map<String, String>>() {}.getType()); String result = HttpClientUtil.postJSON("http://www.test.com/login", json);

關于HttpClient的詳細介紹看這里:HttpClient入門

本文為作者kMacro原創,轉載請注明來源:https://zkhdev.github.io/2018/10/12/java_dev5/。

轉載于:https://www.cnblogs.com/zkh101/p/9777973.html

總結

以上是生活随笔為你收集整理的Java开发小技巧(五):HttpClient工具类的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。