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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

HttpClient 讲解 (2) 项目封装

發布時間:2025/1/21 编程问答 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 HttpClient 讲解 (2) 项目封装 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

2019獨角獸企業重金招聘Python工程師標準>>>

maven加載

<!-- httpclient begin --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.3.4</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpasyncclient</artifactId><version>4.0.2</version></dependency><dependency><groupId>commons-httpclient</groupId><artifactId>commons-httpclient</artifactId><version>3.1</version></dependency><!-- httpclient end -->

請求封裝,自動轉換https

package com.zefun.common.utils;import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.Map;import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager;import org.apache.commons.httpclient.HttpStatus; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; 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.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.BasicHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger;/*** * @author * @date 2015年8月11日 下午2:13:37*/ public class HttpClientUtil {/*** http協議*/private static final String HTTPS_PROTOCOL = "https://";/*** 協議默認端口*/private static final int HTTPS_PROTOCOL_DEFAULT_PORT = 443;/*** 默認編碼格式*/private static final String DEFAULT_CHARSET = "UTF-8";/*** 日志*/private static Logger logger = Logger.getLogger(HttpClientUtil.class);/*** * @author * @date 2015年8月11日 下午2:16:57* @param url 路徑* @return int*/private static int getPort(String url) {int startIndex = url.indexOf("://") + "://".length();String host = url.substring(startIndex);if (host.indexOf("/") != -1) {host = host.substring(0, host.indexOf("/"));}int port = HTTPS_PROTOCOL_DEFAULT_PORT;if (host.contains(":")) {int i = host.indexOf(":");port = new Integer(host.substring(i + 1));}return port;}/*** * @author * @date 2015年8月11日 下午2:14:36* @param params 參數* @return List<NameValuePair>*/private static List<NameValuePair> geneNameValPairs(Map<String, ?> params) {List<NameValuePair> pairs = new ArrayList<NameValuePair>();if (params == null) {return pairs;}for (String name : params.keySet()) {if (params.get(name) == null) {continue;}pairs.add(new BasicNameValuePair(name, params.get(name).toString()));}return pairs;}/*** 發送GET請求* @param url 請求地址* @param charset 返回數據編碼* @return 返回數據*/public static String sendGetReq(final String url, String charset) {if (null == charset){charset = DEFAULT_CHARSET;}CloseableHttpClient httpClient = HttpClientBuilder.create().build();HttpGet get = new HttpGet(url);if (url.toLowerCase().startsWith(HTTPS_PROTOCOL)) {initSSL(httpClient, getPort(url));}try {// 提交請求并以指定編碼獲取返回數據HttpResponse httpResponse = httpClient.execute(get);int statuscode = httpResponse.getStatusLine().getStatusCode();if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)|| (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {Header header = httpResponse.getFirstHeader("location");if (header != null) {String newuri = header.getValue();if ((newuri == null) || (newuri.equals(""))){newuri = "/";}try {httpClient.close();}catch (Exception e) {e.printStackTrace();httpClient = null;}logger.info("重定向地址:" + newuri);return sendGetReq(newuri, null);}}logger.info("請求地址:" + url + ";響應狀態:" + httpResponse.getStatusLine());HttpEntity entity = httpResponse.getEntity();return EntityUtils.toString(entity, charset);}catch (ClientProtocolException e) {logger.error("協議異常,堆棧信息如下", e);}catch (IOException e) {logger.error("網絡異常,堆棧信息如下", e);}finally {// 關閉連接,釋放資源try {httpClient.close();}catch (Exception e) {e.printStackTrace();httpClient = null;}}return null;}/*** 發送put請求* @param url 請求地址* @param params 請求參數* @param charset 返回數據編碼* @return String*/public static String sendPutReq(String url, Map<String, Object> params, String charset) {if (null == charset){charset = DEFAULT_CHARSET;}CloseableHttpClient httpClient = HttpClientBuilder.create().build();HttpPut put = new HttpPut(url);// 封裝請求參數List<NameValuePair> pairs = geneNameValPairs(params);try {put.setEntity(new UrlEncodedFormEntity(pairs, charset));if (url.startsWith(HTTPS_PROTOCOL)) {initSSL(httpClient, getPort(url));}// 提交請求并以指定編碼獲取返回數據HttpResponse httpResponse = httpClient.execute(put);logger.info("請求地址:" + url + ";響應狀態:" + httpResponse.getStatusLine());HttpEntity entity = httpResponse.getEntity();return EntityUtils.toString(entity, charset);}catch (ClientProtocolException e) {logger.error("協議異常,堆棧信息如下", e);}catch (IOException e) {logger.error("網絡異常,堆棧信息如下", e);}finally {// 關閉連接,釋放資源try {httpClient.close();}catch (Exception e) {e.printStackTrace();httpClient = null;}}return null;}/*** 發送delete請求* @param url 請求地址* @param charset 返回數據編碼* @return String*/public static String sendDelReq(String url, String charset) {if (null == charset){charset = DEFAULT_CHARSET;}CloseableHttpClient httpClient = HttpClientBuilder.create().build();HttpDelete del = new HttpDelete(url);if (url.toLowerCase().startsWith(HTTPS_PROTOCOL)) {initSSL(httpClient, getPort(url));}try {// 提交請求并以指定編碼獲取返回數據HttpResponse httpResponse = httpClient.execute(del);logger.info("請求地址:" + url + ";響應狀態:" + httpResponse.getStatusLine());HttpEntity entity = httpResponse.getEntity();return EntityUtils.toString(entity, charset);}catch (ClientProtocolException e) {logger.error("協議異常,堆棧信息如下", e);}catch (IOException e) {logger.error("網絡異常,堆棧信息如下", e);}finally {// 關閉連接,釋放資源try {httpClient.close();}catch (Exception e) {e.printStackTrace();httpClient = null;}}return null;}/*** 發送POST請求,支持HTTP與HTTPS* @param url 請求地址* @param params 請求參數* @param charset 返回數據編碼* @return 返回數據*/public static String sendPostReq(String url, Map<String, ?> params, String charset) {if (null == charset){charset = DEFAULT_CHARSET;}CloseableHttpClient httpClient = HttpClientBuilder.create().build();RequestConfig reqConf = RequestConfig.DEFAULT;HttpPost httpPost = new HttpPost(url);// 封裝請求參數List<NameValuePair> pairs = geneNameValPairs(params);try {httpPost.setEntity(new UrlEncodedFormEntity(pairs, charset));// 對HTTPS請求進行處理if (url.toLowerCase().startsWith(HTTPS_PROTOCOL)) {initSSL(httpClient, getPort(url));}// 提交請求并以指定編碼獲取返回數據httpPost.setConfig(reqConf);HttpResponse httpResponse = httpClient.execute(httpPost);int statuscode = httpResponse.getStatusLine().getStatusCode();if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)|| (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {Header header = httpResponse.getFirstHeader("location");if (header != null) {String newuri = header.getValue();if ((newuri == null) || (newuri.equals(""))){newuri = "/";}try {httpClient.close();}catch (Exception e) {e.printStackTrace();httpClient = null;}return sendGetReq(newuri, null);}}logger.info("請求地址:" + url + ";響應狀態:" + httpResponse.getStatusLine());HttpEntity entity = httpResponse.getEntity();return EntityUtils.toString(entity, charset);}catch (UnsupportedEncodingException e) {logger.error("不支持當前參數編碼格式[" + charset + "],堆棧信息如下", e);}catch (ClientProtocolException e) {logger.error("協議異常,堆棧信息如下", e);}catch (IOException e) {logger.error("網絡異常,堆棧信息如下", e);}finally {// 關閉連接,釋放資源try {httpClient.close();}catch (Exception e) {e.printStackTrace();httpClient = null;}}return null;}/*** 發送POST請求,支持HTTP與HTTPS, 參數放入請求體方式* @param url 請求地址* @param content 請求參數* @param charset 返回數據編碼* @return 返回數據*/public static String sendPost(String url, String content, String charset) {if (null == charset){charset = DEFAULT_CHARSET;}CloseableHttpClient httpClient = HttpClientBuilder.create().build();RequestConfig reqConf = RequestConfig.DEFAULT;HttpPost httpPost = new HttpPost(url);try {httpPost.setEntity(new StringEntity(content, charset));// 對HTTPS請求進行處理if (url.toLowerCase().startsWith(HTTPS_PROTOCOL)) {initSSL(httpClient, getPort(url));}// 提交請求并以指定編碼獲取返回數據httpPost.setConfig(reqConf);HttpResponse httpResponse = httpClient.execute(httpPost);int statuscode = httpResponse.getStatusLine().getStatusCode();if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)|| (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {Header header = httpResponse.getFirstHeader("location");if (header != null) {String newuri = header.getValue();if ((newuri == null) || (newuri.equals(""))){newuri = "/";}try {httpClient.close();}catch (Exception e) {e.printStackTrace();httpClient = null;}return sendGetReq(newuri, null);}}logger.info("請求地址:" + url + ";響應狀態:" + httpResponse.getStatusLine());HttpEntity entity = httpResponse.getEntity();return EntityUtils.toString(entity, charset);}catch (UnsupportedEncodingException e) {logger.error("不支持當前參數編碼格式[" + charset + "],堆棧信息如下", e);}catch (ClientProtocolException e) {logger.error("協議異常,堆棧信息如下", e);}catch (IOException e) {logger.error("網絡異常,堆棧信息如下", e);}finally {// 關閉連接,釋放資源try {httpClient.close();}catch (Exception e) {e.printStackTrace();httpClient = null;}}return null;}/*** 初始化HTTPS請求服務* @param httpClient HTTP客戶端* @param port 端口*/public static void initSSL(CloseableHttpClient httpClient, int port) {SSLContext sslContext = null;try {sslContext = SSLContext.getInstance("SSL");final X509TrustManager trustManager = new X509TrustManager() {public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}public X509Certificate[] getAcceptedIssuers() {return null;}};// 使用TrustManager來初始化該上下文,TrustManager只是被SSL的Socket所使用sslContext.init(null, new TrustManager[] { trustManager }, null);ConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sslContext);Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory> create().register("https", ssf).build();BasicHttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(r);HttpClients.custom().setConnectionManager(ccm).build();}catch (KeyManagementException e) {e.printStackTrace();}catch (NoSuchAlgorithmException e) {e.printStackTrace();}} }

調用請求

String url = "http://up.qiniu.com/putb64/-1";HttpPost post = new HttpPost(url);post.addHeader("Content-Type", "application/octet-stream");post.addHeader("Authorization", "UpToken " + qiniuUptoken().get("uptoken"));//post.setEntity(new ByteArrayEntity(src));post.setEntity(new StringEntity(stringBase64));HttpClient c = Http.getClient();HttpResponse res = c.execute(post);System.out.println(res.getStatusLine().getReasonPhrase());String responseBody = EntityUtils.toString(res.getEntity(), Config.CHARSET);System.out.println(responseBody);

上傳文件

基于File上傳

File file = new File("d:\\1.jpg");FileBody body = new FileBody(file);MultipartEntity entity = new MultipartEntity();//注意file是在后臺中接受的參數File fileentity.addPart("file", body);httpPost.setEntity(entity);

基于流上傳

InputStreamBody inputStreamBody = new InputStreamBody(new FileInputStream(file), file.getName());MultipartEntity entity = new MultipartEntity();//注意file是在后臺中接受的參數File fileentity.addPart("file", inputStreamBody);httpPost.setEntity(entity);
后臺接受都是一樣的

@RequestMapping(value = Url.Project.UPLOAD_PROJECT)public BaseDto uploadTest(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request){String path = request.getSession().getServletContext().getRealPath("upload"); String fileName = file.getOriginalFilename(); File targetFile = new File(path, fileName); if (!targetFile.exists()){ targetFile.mkdir();} try { file.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); }return new BaseDto(App.System.API_RESULT_CODE_FOR_SUCCEES, App.System.API_RESULT_MSG_FOR_SUCCEES);}

轉載于:https://my.oschina.net/gaoguofan/blog/752914

總結

以上是生活随笔為你收集整理的HttpClient 讲解 (2) 项目封装的全部內容,希望文章能夠幫你解決所遇到的問題。

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