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) 项目封装相关推荐

  1. jsoup教程_2 http-client 讲解

    项目源代码 https://gitee.com/fakerlove/jsoup 文章目录 2. http-client 讲解 2.1 get 请求 2.2 get带请求 工具类 发送请求 2.3 Po ...

  2. Interview:算法岗位面试—10.17早上—上海某科技公司算法岗位(偏算法,独角兽)非技术面试之比赛项目讲解和项目意义的探讨

    Interview:算法岗位面试-10.17早上-上海某科技公司算法岗位(偏算法,独角兽)非技术面试之比赛项目讲解和项目意义的探讨 导读:今天某科技独角兽让我去面试,但是与另一家银行相冲突,先去了银行 ...

  3. java 博客系统_讲解开源项目:5分钟搭建私人Java博客系统

    本文适合刚学习完 Java 语言基础的人群,跟着本文可了解和运行 Tale 项目.示例均在 Windows 操作系统下演示 本文作者:HelloGitHub-秦人 HelloGitHub 推出的< ...

  4. swift5表情键盘项目封装

    swift5表情键盘项目封装 地址https://gitee.com/johnson__save_admin/emoji_-key-board

  5. 讲解开源项目:让你成为灵魂画手的 JS 引擎:Zdog

    本文作者:HelloGitHub-kalifun HelloGitHub 的<讲解开源项目>系列,项目地址:https://github.com/HelloGitHub-Team/Arti ...

  6. 讲解开源项目:用 Python 生成有“灵魂”的二维码

    本文作者:HelloGitHub-LITTLECHIEH 这是 HelloGitHub 推出的<讲解开源项目>系列,今天给大家推荐一个 Python 开源生成二维码的项目--qrcode ...

  7. 讲解开源项目:一步步跑起来个 Java 前后端分离的人力资源管理系统

    本文适合刚学习完 Java 语言基础的人群,跟着本文可了解和运行项目,本示例是在 Windows 操作系统下演示. 本文作者:HelloGitHub-秦人 大家好!这里是 HelloGitHub 推出 ...

  8. Vue3+TypeScript 项目封装axios

    Vue3+TypeScript 项目封装axios VUE CLI 中代码目录解构 config.js let BASE_URL = '' const TIME_OUT = 10000 //区分环境不 ...

  9. 怎么把html封装成桌面应用,如何将一个现有的Vue网页项目封装成electron桌面应用...

    需求缘由 开发了很久的网页项目,领导突然想变成桌面应用,又要重写代码?no,no,no.不可能的.重写代码吃力不讨好,浪费时间,浪费精力.那么我们该怎么办呢? 幸好,electron是如此神奇,它提供 ...

最新文章

  1. 用计算机画函数图像教案,信息技术应用 用计算机画函数图象教案1
  2. 计算n!中结尾零的个数
  3. GitHub 中文文档正式发布了!激动人心的大好事!
  4. openssl 64位编译_海思hi3516dv300开发--live555交叉编译
  5. 利用水的浮力测量物体的重量,这个方法称象可靠吗?
  6. LeetCode 92反转链表||-中等
  7. 《朝花夕拾》金句摘抄(四)
  8. java----连接池C3p0使用的补充
  9. 初学必读:61条面向对象设计的经验原则
  10. python百度翻译爬虫_Python爬虫教程-05-python爬虫实现百度翻译
  11. 《Go学习笔记 . 雨痕》流程控制(if、switch、for range、goto、continue、break)
  12. Pyhton学习——Day33
  13. Windows 命令使用之 ping 命令
  14. Connection could not be established with host smtp.163.com 阿星小栈
  15. js 空数组直接赋值与push
  16. NOIP提高组 单峰
  17. Adobe Photoshop 输出ICO格式图标文件
  18. configure 中常见的几个命令
  19. 组态王客户端显示服务器画面,组态王客户端显示服务器画面
  20. 幽默笑话,来不及脱裤子,木子家原创

热门文章

  1. 常见荧光定量 PCR 检测方法比较
  2. OriginPro 2021安装教程(手把手式安装)
  3. exe一机一码加密工具_文件夹加密软件有哪些作用?
  4. HTML+CSS+JavaScript复习笔记持更(一)——标签篇
  5. Java与C#比较,哪个语言更是适合你?
  6. 对文本根据特殊字符进行分段代码_如何优雅地配置快应用的代码片段
  7. 用python做逻辑回归梯度上升_机器学习实例---4.1、Logistic回归基础篇之梯度上升算法...
  8. PowerBI随笔(5)-关系模型与报表-2
  9. 799页!吴恩达深度学习笔记.PDF
  10. 【机器学习基础】Python实现行转列?!超简单,赶快get起来