<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.58</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5.3</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.13</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.7</version> </dependency>
該工具類將get請求和post請求當中幾種傳參方式都寫了,其中有get位址列傳參、get的params傳參、post的params傳參、post的json傳參。
import com.alibaba.fastjson.JSONObject; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Map; public class HttpClientUtil { private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class); private static final int DEFULT_TIMEOUT = 30 * 1000;//預設超時時間20秒 /** * 可以存取 http://localhost:9005/yzhwsj/addPersonal/1/2 這樣的介面 * @param url * @param headers * @param urlParam * @param timeout * @return */ private static String doUrlGet(String url, Map<String, String> headers, List<String> urlParam, Integer timeout) { //建立httpClient物件 CloseableHttpClient httpClient = HttpClients.createDefault(); String resultString = null; CloseableHttpResponse response = null; try { //建立uri if (urlParam != null){ for (String param : urlParam) { url = url + "/" + param; } } //建立hTTP get請求 HttpGet httpGet = new HttpGet(url); //設定超時時間 int timeoutTmp = DEFULT_TIMEOUT; if (timeout != null) { timeoutTmp = timeout; } RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp) .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build(); httpGet.setConfig(requestConfig); //設定頭資訊 if (null != headers) { for (String key : headers.keySet()) { httpGet.setHeader(key, headers.get(key)); } } //執行請求 response = httpClient.execute(httpGet); if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8); } } catch (IOException e) { logger.error("http呼叫異常" + e.toString(), e); } finally { try { if (null != response) { response.close(); } } catch (IOException e) { logger.error("response關閉異常" + e.toString(), e); } try { if (null != httpClient) { httpClient.close(); } } catch (IOException e) { logger.error("httpClient關閉異常" + e.toString(), e); } } return resultString; } /** * @param url * @param headers * @param params * @param timeout * @return */ private static String doGet(String url, Map<String, String> headers, Map<String, Object> params, Integer timeout) { //建立httpClient物件 CloseableHttpClient httpClient = HttpClients.createDefault(); String resultString = null; CloseableHttpResponse response = null; try { // 1.建立uri URIBuilder builder = new URIBuilder(url); if (params != null) { //uri新增引數 for (String key : params.keySet()) { builder.addParameter(key, String.valueOf(params.get(key))); } } URI uri = builder.build(); // 2.建立hTTP get請求 HttpGet httpGet = new HttpGet(uri); // 3.設定超時時間 int timeoutTmp = DEFULT_TIMEOUT; if (timeout != null) { timeoutTmp = timeout; } RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp) .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build(); httpGet.setConfig(requestConfig); // 4.設定頭資訊 if (null != headers) { for (String key : headers.keySet()) { httpGet.setHeader(key, headers.get(key)); } } // 5.執行請求 response = httpClient.execute(httpGet); if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8); } } catch (URISyntaxException e) { logger.error("http呼叫異常" + e.toString(), e); } catch (IOException e) { logger.error("http呼叫異常" + e.toString(), e); } finally { try { if (null != response) { response.close(); } } catch (IOException e) { logger.error("response關閉異常" + e.toString(), e); } try { if (null != httpClient) { httpClient.close(); } } catch (IOException e) { logger.error("httpClient關閉異常" + e.toString(), e); } } return resultString; } /** * 呼叫http post請求(json資料) * * @param url * @param headers * @param json * @return */ public static String doJsonPost(String url, Map<String, String> headers, JSONObject json, Integer timeout) { CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 1.建立http post請求 HttpPost httpPost = new HttpPost(url); // 2.設定超時時間 int timeoutTmp = DEFULT_TIMEOUT; if (timeout != null) { timeoutTmp = timeout; } RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp) .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build(); httpPost.setConfig(requestConfig); // 3.設定引數資訊 StringEntity s = new StringEntity(json.toString(), Consts.UTF_8); // 傳送json資料需要設定的contentType s.setContentType("application/json"); httpPost.setEntity(s); // 4.設定頭資訊 if (headers != null) { for (String key : headers.keySet()) { httpPost.setHeader(key, headers.get(key)); } } // 5.執行http請求 response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8); } } catch (UnsupportedEncodingException e) { logger.error("呼叫http異常" + e.toString(), e); } catch (ClientProtocolException e) { logger.error("呼叫http異常" + e.toString(), e); } catch (IOException e) { logger.error("呼叫http異常" + e.toString(), e); } finally { try { if (null != response) { response.close(); } } catch (IOException e) { logger.error("關閉response異常" + e.toString(), e); } try { if (null != httpClient) { httpClient.close(); } } catch (IOException e) { logger.error("關閉httpClient異常" + e.toString(), e); } } return resultString; } /** * 呼叫http post請求 基礎方法 * * @param url 請求的url * @param headers 請求頭 * @param params 引數 * @param timeout 超時時間 * @return */ public static String doPost(String url, Map<String, String> headers, Map<String, Object> params, Integer timeout) { CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 1.建立http post請求 HttpPost httpPost = new HttpPost(url); // 2.設定超時時間 int timeoutTmp = DEFULT_TIMEOUT; if (timeout != null) { timeoutTmp = timeout; } RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp) .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build(); httpPost.setConfig(requestConfig); // 3.設定引數資訊 if (params != null) { List<NameValuePair> paramList = new ArrayList<>(); for (String key : params.keySet()) { paramList.add(new BasicNameValuePair(key, String.valueOf(params.get(key)))); } // 模擬表單 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, Consts.UTF_8); httpPost.setEntity(entity); } // 4.設定頭資訊 if (headers != null) { for (String key : headers.keySet()) { httpPost.setHeader(key, headers.get(key)); } } // 5.執行http請求 response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8); } } catch (UnsupportedEncodingException e) { logger.error("呼叫http異常" + e.toString(), e); } catch (ClientProtocolException e) { logger.error("呼叫http異常" + e.toString(), e); } catch (IOException e) { logger.error("呼叫http異常" + e.toString(), e); } finally { try { if (null != response) { response.close(); } } catch (IOException e) { logger.error("關閉response異常" + e.toString(), e); } try { if (null != httpClient) { httpClient.close(); } } catch (IOException e) { logger.error("關閉httpClient異常" + e.toString(), e); } } return resultString; } /** * 通過httpClient上傳檔案 * * @param url 請求的URL * @param headers 請求頭引數 * @param path 檔案路徑 * @param fileName 檔名稱 * @param timeout 超時時間 * @return */ public static String UploadFileByHttpClient(String url, Map<String, String> headers, String path, String fileName, Integer timeout) { String resultString = ""; CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; InputStream content = null; BufferedReader in = null; try { // 1.建立http post請求 HttpPost httpPost = new HttpPost(url); // 2.設定超時時間 int timeoutTmp = DEFULT_TIMEOUT; if (timeout != null) { timeoutTmp = timeout; } RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp) .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build(); httpPost.setConfig(requestConfig); // 3.設定引數資訊 // HttpMultipartMode.RFC6532引數的設定是為避免檔名為中文時亂碼 MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532); // 上傳檔案的路徑 File file = new File(path + File.separator + fileName); builder.setCharset(Charset.forName("UTF-8")); builder.addBinaryBody("file", file, ContentType.MULTIPART_FORM_DATA, fileName); HttpEntity entity = builder.build(); httpPost.setEntity(entity); // 4.設定頭資訊 if (headers != null) { for (String key : headers.keySet()) { httpPost.setHeader(key, headers.get(key)); } } // 5.執行http請求 response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8); } } catch (Exception e) { logger.error("上傳檔案失敗:", e); } finally { try { if (null != httpClient) { httpClient.close(); } } catch (IOException e) { logger.error("關閉httpClient異常" + e.toString(), e); } try { if (null != content) { content.close(); } } catch (IOException e) { logger.error("關閉content異常" + e.toString(), e); } try { if (null != in) { in.close(); } } catch (IOException e) { logger.error("關閉in異常" + e.toString(), e); } } return resultString; } } /** * 通過httpClient批次上傳檔案 * * @param url 請求的URL * @param headers 請求頭引數 * @param params 引數 * @param paths 檔案路徑(key檔名稱,value路徑) * @param timeout 超時時間 * @return */ public static String UploadFilesByHttpClient(String url, Map<String, String> headers, Map<String, String> params, Map<String, String> paths, Integer timeout) { String resultString = ""; CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; InputStream content = null; BufferedReader in = null; try { // 1.建立http post請求 HttpPost httpPost = new HttpPost(url); // 2.設定超時時間 int timeoutTmp = DEFULT_TIMEOUT; if (timeout != null) { timeoutTmp = timeout; } RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp) .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build(); httpPost.setConfig(requestConfig); // 3.設定檔案資訊 // HttpMultipartMode.RFC6532引數的設定是為避免檔名為中文時亂碼 MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532); builder.setCharset(Charset.forName("UTF-8")); // 上傳檔案的路徑 for (Map.Entry<String, String> m : paths.entrySet()) { File file = new File(m.getValue() + File.separator + m.getKey()); builder.addBinaryBody("files", file, ContentType.MULTIPART_FORM_DATA, m.getKey()); } // 4.設定引數資訊 ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8")); for (Map.Entry<String, String> param : params.entrySet()) { builder.addTextBody(param.getKey(), param.getValue(), contentType); } HttpEntity entity = builder.build(); httpPost.setEntity(entity); // 5.設定頭資訊 if (headers != null) { for (String key : headers.keySet()) { httpPost.setHeader(key, headers.get(key)); } } // 6.執行http請求 response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8); } } catch (Exception e) { logger.error("上傳檔案失敗:", e); } finally { try { if (null != httpClient) { httpClient.close(); } } catch (IOException e) { logger.error("關閉httpClient異常" + e.toString(), e); } try { if (null != content) { content.close(); } } catch (IOException e) { logger.error("關閉content異常" + e.toString(), e); } try { if (null != in) { in.close(); } } catch (IOException e) { logger.error("關閉in異常" + e.toString(), e); } } return resultString; }
上面的工具類,方法都攜帶了token和超時時間,假如介面用不到可以做介面拓展。例如:
/** * 呼叫http get請求 * * @param url * @param params * @return */ public static String doGet(String url, Map<String, Object> params) { return doGet(url, null, params, null); }
如果涉及到put請求和delete請求,跟上面都差不多,只不過建立請求的時候改為:
HttpDelete httpDelete = new HttpDelete(); HttpPut httpPut = new HttpPut();
到此這篇關於HttpClient詳細使用範例的文章就介紹到這了,更多相關HttpClient使用內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!
相關文章
<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
综合看Anker超能充系列的性价比很高,并且与不仅和iPhone12/苹果<em>Mac</em>Book很配,而且适合多设备充电需求的日常使用或差旅场景,不管是安卓还是Switch同样也能用得上它,希望这次分享能给准备购入充电器的小伙伴们有所
2021-06-01 09:31:42
除了L4WUDU与吴亦凡已经多次共事,成为了明面上的厂牌成员,吴亦凡还曾带领20XXCLUB全队参加2020年的一场音乐节,这也是20XXCLUB首次全员合照,王嗣尧Turbo、陈彦希Regi、<em>Mac</em> Ova Seas、林渝植等人全部出场。然而让
2021-06-01 09:31:34
目前应用IPFS的机构:1 谷歌<em>浏览器</em>支持IPFS分布式协议 2 万维网 (历史档案博物馆)数据库 3 火狐<em>浏览器</em>支持 IPFS分布式协议 4 EOS 等数字货币数据存储 5 美国国会图书馆,历史资料永久保存在 IPFS 6 加
2021-06-01 09:31:24
开拓者的车机是兼容苹果和<em>安卓</em>,虽然我不怎么用,但确实兼顾了我家人的很多需求:副驾的门板还配有解锁开关,有的时候老婆开车,下车的时候偶尔会忘记解锁,我在副驾驶可以自己开门:第二排设计很好,不仅配置了一个很大的
2021-06-01 09:30:48
不仅是<em>安卓</em>手机,苹果手机的降价力度也是前所未有了,iPhone12也“跳水价”了,发布价是6799元,如今已经跌至5308元,降价幅度超过1400元,最新定价确认了。iPhone12是苹果首款5G手机,同时也是全球首款5nm芯片的智能机,它
2021-06-01 09:30:45