httpclient4.3 工具类
httpclient4.3 java工具类。
。。
。因项目须要开发了一个工具类。正经常常使用的httpclient 请求操作应该都够用了
工具类下载地址:http://download.csdn.net/detail/ruishenh/7421641
- package com.ruishenh.utils;
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import java.net.URISyntaxException;
- import java.nio.charset.Charset;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import org.apache.commons.httpclient.HttpStatus;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpException;
- import org.apache.http.HttpResponse;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.ClientProtocolException;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.config.RequestConfig;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.client.methods.HttpRequestBase;
- import org.apache.http.client.utils.URLEncodedUtils;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClientBuilder;
- import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.protocol.HTTP;
- import org.apache.http.util.EntityUtils;
- public class HttpClientUtils {
- /**
- * 连接超时时间
- */
- public static final int CONNECTION_TIMEOUT_MS = 360000;
- /**
- * 读取数据超时时间
- */
- public static final int SO_TIMEOUT_MS = 360000;
- public static final String CONTENT_TYPE_JSON_CHARSET = "application/json;charset=gbk";
- public static final String CONTENT_TYPE_XML_CHARSET = "application/xml;charset=gbk";
- /**
- * httpclient读取内容时使用的字符集
- */
- public static final String CONTENT_CHARSET = "GBK";
- public static final Charset UTF_8 = Charset.forName("UTF-8");
- public static final Charset GBK = Charset.forName(CONTENT_CHARSET);
- /**
- * 简单get调用
- *
- * @param url
- * @param params
- * @return
- * @throws ClientProtocolException
- * @throws IOException
- * @throws URISyntaxException
- */
- public static String simpleGetInvoke(String url, Map<String, String> params)
- throws ClientProtocolException, IOException, URISyntaxException {
- return simpleGetInvoke(url, params,CONTENT_CHARSET);
- }
- /**
- * 简单get调用
- *
- * @param url
- * @param params
- * @return
- * @throws ClientProtocolException
- * @throws IOException
- * @throws URISyntaxException
- */
- public static String simpleGetInvoke(String url, Map<String, String> params,String charset)
- throws ClientProtocolException, IOException, URISyntaxException {
- HttpClient client = buildHttpClient(false);
- HttpGet get = buildHttpGet(url, params);
- HttpResponse response = client.execute(get);
- assertStatus(response);
- HttpEntity entity = response.getEntity();
- if (entity != null) {
- String returnStr = EntityUtils.toString(entity,charset);
- return returnStr;
- }
- return null;
- }
- /**
- * 简单post调用
- *
- * @param url
- * @param params
- * @return
- * @throws URISyntaxException
- * @throws ClientProtocolException
- * @throws IOException
- */
- public static String simplePostInvoke(String url, Map<String, String> params)
- throws URISyntaxException, ClientProtocolException, IOException {
- return simplePostInvoke(url, params,CONTENT_CHARSET);
- }
- /**
- * 简单post调用
- *
- * @param url
- * @param params
- * @return
- * @throws URISyntaxException
- * @throws ClientProtocolException
- * @throws IOException
- */
- public static String simplePostInvoke(String url, Map<String, String> params,String charset)
- throws URISyntaxException, ClientProtocolException, IOException {
- HttpClient client = buildHttpClient(false);
- HttpPost postMethod = buildHttpPost(url, params);
- HttpResponse response = client.execute(postMethod);
- assertStatus(response);
- HttpEntity entity = response.getEntity();
- if (entity != null) {
- String returnStr = EntityUtils.toString(entity, charset);
- return returnStr;
- }
- return null;
- }
- /**
- * 创建HttpClient
- *
- * @param isMultiThread
- * @return
- */
- public static HttpClient buildHttpClient(boolean isMultiThread) {
- CloseableHttpClient client;
- if (isMultiThread)
- client = HttpClientBuilder
- .create()
- .setConnectionManager(
- new PoolingHttpClientConnectionManager()).build();
- else
- client = HttpClientBuilder.create().build();
- // 设置代理server地址和端口
- // client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);
- return client;
- }
- /**
- * 构建httpPost对象
- *
- * @param url
- * @param headers
- * @return
- * @throws UnsupportedEncodingException
- * @throws URISyntaxException
- */
- public static HttpPost buildHttpPost(String url, Map<String, String> params)
- throws UnsupportedEncodingException, URISyntaxException {
- Assert.notNull(url, "构建HttpPost时,url不能为null");
- HttpPost post = new HttpPost(url);
- setCommonHttpMethod(post);
- HttpEntity he = null;
- if (params != null) {
- List<NameValuePair> formparams = new ArrayList<NameValuePair>();
- for (String key : params.keySet()) {
- formparams.add(new BasicNameValuePair(key, params.get(key)));
- }
- he = new UrlEncodedFormEntity(formparams, GBK);
- post.setEntity(he);
- }
- // 在RequestContent.process中会自己主动写入消息体的长度,自己不用写入。写入反而检測报错
- // setContentLength(post, he);
- return post;
- }
- /**
- * 构建httpGet对象
- *
- * @param url
- * @param headers
- * @return
- * @throws URISyntaxException
- */
- public static HttpGet buildHttpGet(String url, Map<String, String> params)
- throws URISyntaxException {
- Assert.notNull(url, "构建HttpGet时,url不能为null");
- HttpGet get = new HttpGet(buildGetUrl(url, params));
- return get;
- }
- /**
- * build getUrl str
- *
- * @param url
- * @param params
- * @return
- */
- private static String buildGetUrl(String url, Map<String, String> params) {
- StringBuffer uriStr = new StringBuffer(url);
- if (params != null) {
- List<NameValuePair> ps = new ArrayList<NameValuePair>();
- for (String key : params.keySet()) {
- ps.add(new BasicNameValuePair(key, params.get(key)));
- }
- uriStr.append("?");
- uriStr.append(URLEncodedUtils.format(ps, UTF_8));
- }
- return uriStr.toString();
- }
- /**
- * 设置HttpMethod通用配置
- *
- * @param httpMethod
- */
- public static void setCommonHttpMethod(HttpRequestBase httpMethod) {
- httpMethod.setHeader(HTTP.CONTENT_ENCODING, CONTENT_CHARSET);// setting
- // contextCoding
- // httpMethod.setHeader(HTTP.CHARSET_PARAM, CONTENT_CHARSET);
- // httpMethod.setHeader(HTTP.CONTENT_TYPE, CONTENT_TYPE_JSON_CHARSET);
- // httpMethod.setHeader(HTTP.CONTENT_TYPE, CONTENT_TYPE_XML_CHARSET);
- }
- /**
- * 设置成消息体的长度 setting MessageBody length
- *
- * @param httpMethod
- * @param he
- */
- public static void setContentLength(HttpRequestBase httpMethod,
- HttpEntity he) {
- if (he == null) {
- return;
- }
- httpMethod.setHeader(HTTP.CONTENT_LEN, String.valueOf(he.getContentLength()));
- }
- /**
- * 构建公用RequestConfig
- *
- * @return
- */
- public static RequestConfig buildRequestConfig() {
- // 设置请求和传输超时时间
- RequestConfig requestConfig = RequestConfig.custom()
- .setSocketTimeout(SO_TIMEOUT_MS)
- .setConnectTimeout(CONNECTION_TIMEOUT_MS).build();
- return requestConfig;
- }
- /**
- * 强验证必须是200状态否则报异常
- * @param res
- * @throws HttpException
- */
- static void assertStatus(HttpResponse res) throws IOException{
- Assert.notNull(res, "http响应对象为null");
- Assert.notNull(res.getStatusLine(), "http响应对象的状态为null");
- switch (res.getStatusLine().getStatusCode()) {
- case HttpStatus.SC_OK:
- // case HttpStatus.SC_CREATED:
- // case HttpStatus.SC_ACCEPTED:
- // case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
- // case HttpStatus.SC_NO_CONTENT:
- // case HttpStatus.SC_RESET_CONTENT:
- // case HttpStatus.SC_PARTIAL_CONTENT:
- // case HttpStatus.SC_MULTI_STATUS:
- break;
- default:
- throw new IOException("server响应状态异常,失败.");
- }
- }
- private HttpClientUtils() {
- }
- public static void main(String[] args) throws ClientProtocolException, IOException, URISyntaxException {
- System.out.println(simpleGetInvoke("http://www.baidu.com", new HashMap<String, String>()));
- }
- }
httpclient4.3 工具类的更多相关文章
- 基于HttpClient4.5.1实现Http访问工具类
本工具类基于httpclient4.5.1实现 <dependency> <groupId>org.apache.httpcomponents</groupId> ...
- HttpClient4.5 SSL访问工具类
要从网上找一个HttpClient SSL访问工具类太难了,原因是HttpClient版本太多了,稍有差别就不能用,最后笔者干脆自己封装了一个访问HTTPS并绕过证书工具类. 主要是基于新版本Http ...
- 基于HttpClient4.5.2实现的HttpClient工具类
1.maven依赖: <dependency> <groupId>org.apache.commons</groupId> <artifactId>co ...
- java http工具类和HttpUrlConnection上传文件分析
利用java中的HttpUrlConnection上传文件,我们其实只要知道Http协议上传文件的标准格式.那么就可以用任何一门语言来模拟浏览器上传文件.下面有几篇文章从http协议入手介绍了java ...
- 验证工具类 - ValidateUtils.java
验证工具类,提供验证email格式.是否ipv4.是否ipv6.是否中文.是否数字.正则表达式验证的方法. 源码如下:(点击下载 - ValidateUtils.java .commons-lang- ...
- Jsoup请求http或https返回json字符串工具类
Jsoup请求http或https返回json字符串工具类 所需要的jar包如下: jsoup-1.8.1.jar 依赖jar包如下: httpclient-4.5.4.jar; httpclient ...
- 小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_5-5.HttpClient4.x工具获取使用
笔记 5.HttpClient4.x工具获取使用 简介:讲解httpClient4.x相关依赖,并封装基本方法. 1.加入依赖 <dependency> ...
- Java基础Map接口+Collections工具类
1.Map中我们主要讲两个接口 HashMap 与 LinkedHashMap (1)其中LinkedHashMap是有序的 怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...
- Android—关于自定义对话框的工具类
开发中有很多地方会用到自定义对话框,为了避免不必要的城府代码,在此总结出一个工具类. 弹出对话框的地方很多,但是都大同小异,不同无非就是提示内容或者图片不同,下面这个类是将提示内容和图片放到了自定义函 ...
随机推荐
- System.Drawing.Design.UITypeEditor自定义控件属性GetEditStyle(ITypeDescriptorContext context),EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.C ...
- poj2014 不带修改区间第k大树
主席树 又称函数式线段树,又称可持久化线段树……缺点是内存有点儿大…… type node1=record l,r,sum:longint; end; node2=record x,idx:longi ...
- WinCE发展史
Windows CE概述 WindowsCE是微软公司嵌入式.移动计算平台的基础,它是一个开放的.可升级的32位嵌入式操作系统,是基于掌上型电脑类的电子设备操作系统,它是精简的Windows 95,W ...
- 【spring-boot】快速构建spring-boot微框架
spring-boot是一个快速构建环境的一套框架,其设计理念是尽可能的减少xml的配置,用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义 ...
- OA,ERP等源码一部分演示
更多源码http://www.pssdss.com QQ:11851298 功能强大的JAVA开发的ERP源码http://cx050027.pssdss.com:8080/ 用户名pssdss ...
- iOS开发中提交带有中文或特殊字符串的参数
iOS开发中,与后台进行数据交换是一个很常见的场景. 在web开发中,对于我们提交的地址,浏览器会负责进行decode,但是在ios中,必须要自己手动来实现.否则我们拼接出的网址在包括中文.特殊字符串 ...
- java中的final关键字
谈到final关键字,想必很多人都不陌生,在使用匿名内部类的时候可能会经常用到final关键字.另外,Java中的String类就是一个final类,那么今天我们就来了解final这个关键字的用法.下 ...
- order by优化--Order By实现原理分析和Filesort优化
在MySQL中的ORDER BY有两种排序实现方式: 1.利用有序索引获取有序数据 2.文件排序 在使用explain分析查询的时候,利用有序索引获取有序数据显示Using index.而文件排序显示 ...
- Mac下安装Mysql出现 Can’t connect to local MySQL server through socket '/tmp/mysql.sock'
在Mac下安装mysql出现 Can't connect to local MySQL server through socket '/tmp/mysql.sock' 错误,解决如下: $ unset ...
- 第二个App“今日美文”上架【原】
App store 下载地址 开发这个App的本意 之前偶然找到一个叫<每日一文>的应用,正是我一直想找的,优点如下: 界面够简单 推荐的文章也很好,而且都不太长 每天都不一样 但是用起来 ...