`

小插件HttpClient

阅读更多

package com.sound.cloudpos.base.util;

 

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.net.UnknownHostException;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import java.util.Set;

import java.util.concurrent.ConcurrentHashMap;

 

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

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.methods.HttpUriRequest;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;

import org.apache.http.impl.client.HttpClientBuilder;

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 com.alibaba.druid.util.StringUtils;

import com.alibaba.dubbo.common.json.JSON;

import com.sound.cloudpos.base.exception.HttpClientException;

 

import net.sf.json.JSONObject;

 

/**

 * httpClient工具类<br/>

 * 提供post和get的接口调用

 * 

 * @author chenrui

 *

 */

public class HttpClientUtil {

static Logger logger = LoggerFactory.getLogger("HttpClientUtil.class");

private static final String PRO_FILE_PATH = "httpclient.properties";

 

/**

* 超时时间,默认5000

*/

private static Integer timeout = 5000;

/**

* 重试次数,默认3次

*/

private static Integer retryTimes = 3;

 

/**

* 初始化超时时间和重试次数

*/

static {

ProfileUtil profileUtil = ProfileUtil.getInstance();

String _timeout = profileUtil.read(PRO_FILE_PATH, "client.timeout");

String _retryTimes = profileUtil.read(PRO_FILE_PATH, "client.retry_times");

if (!StringUtils.isEmpty(_timeout)) {

timeout = Integer.parseInt(_timeout);

}

if (!StringUtils.isEmpty(_retryTimes)) {

retryTimes = Integer.parseInt(_retryTimes);

}

}

 

/**

* 创建httpClient,创建时设置超时时间和重试次数

* @return

*/

private static CloseableHttpClient createClient() {

HttpClientBuilder clientBuilder = HttpClients.custom();

RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)

.setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();

// 设置重试次数

clientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryTimes, true));

// 设置超时时间

clientBuilder.setDefaultRequestConfig(requestConfig);

return clientBuilder.build();

}

 

/**

* 执行post请求,返回String类型的返回值

* @param url

* @param params <String,String>的Map类型参数

* @return

* @throws IOException

* @throws HttpClientException 

*/

public static String post(String url, Map<String, String> headers, Map<String, String> params) throws IOException, HttpClientException {

CloseableHttpClient httpclient = createClient();

 

String body = null;

 

logger.info("create httppost:" + url);

HttpPost post = postForm(url,headers, params);

try {

body = invoke(httpclient, post);

} catch (HttpClientException e) {

throw e;

} catch (UnknownHostException e) {

throw new HttpClientException(404);

} catch (Exception e) {

throw e;

} finally {

httpclient.close();

}

 

return body;

}

 

/**

* 执行post请求,返回String类型的返回值

* @param url

* @param params <String,String>的Map类型参数

* @return

* @throws IOException

* @throws HttpClientException 

*/

public static String post(String url, Map<String, String> headers) throws IOException, HttpClientException {

CloseableHttpClient httpclient = createClient();

 

String body = null;

 

logger.info("create httppost:" + url);

HttpPost httpost = new HttpPost(url);

 

if (null != headers) {

for (String key : headers.keySet()) {

httpost.setHeader(key, headers.get(key));

}

}

try {

body = invoke(httpclient, httpost);

} catch (HttpClientException e) {

throw e;

} catch (UnknownHostException e) {

throw new HttpClientException(404);

} catch (Exception e) {

throw e;

} finally {

httpclient.close();

}

return body;

}

 

/**

* 执行post请求,返回String类型的返回值 设置cookie

* @param url

* @param params <String,String>的Map类型参数

* @return

* @throws IOException

* @throws HttpClientException 

*/

public static String postAndCookie(String url, Map<String, String> headers,Map<String,String> cookieMap) throws IOException, HttpClientException {

CloseableHttpClient httpclient = createClient();

String body = null;

 

logger.info("create httppost:" + url);

HttpPost httpost = new HttpPost(url);

StringBuilder cookieStr = new StringBuilder(); 

if(null != cookieMap){

for(Entry<String, String> entry : cookieMap.entrySet()){

String name = entry.getKey();

String value = entry.getValue();

cookieStr.append(name).append('=').append(value).append(';');  

}

cookieStr.deleteCharAt(cookieStr.length() - 1);

}

if (null != headers) {

for (String key : headers.keySet()) {

httpost.setHeader(key, headers.get(key));

httpost.setHeader("Cookie", cookieStr.toString());

}

}

 

try {

body = invoke(httpclient, httpost);

} catch (HttpClientException e) {

throw e;

} catch (UnknownHostException e) {

throw new HttpClientException(404);

} catch (Exception e) {

throw e;

} finally {

httpclient.close();

}

return body;

}

 

/**

* 执行get请求,返回String类型的请求

* @param url

* @return

* @throws IOException

* @throws HttpClientException

*/

public static String get(String url) throws IOException, HttpClientException {

CloseableHttpClient httpclient = createClient();

String body = null;

logger.info("create httpget:" + url);

HttpGet get = new HttpGet(url);

try {

body = invoke(httpclient, get);

} catch (HttpClientException e) {

throw e;

} catch (UnknownHostException e) {

throw new HttpClientException(404);

} catch (Exception e) {

throw e;

} finally {

httpclient.close();

}

 

return body;

}

 

/**

* 执行get请求,返回String类型的请求

* @param url

* @param params

* @return

* @throws IOException

* @throws HttpClientException

*/

public static String getOfParams(String url,Map<String,String> params) throws IOException, HttpClientException {

if (params != null&&params.size() > 0) {

           StringBuffer sb = new StringBuffer();

           if (url.indexOf("?") == -1) {

               url += "?";

           } else {

               url += "&";

           }

           for (ConcurrentHashMap.Entry<String, String> entry : params.entrySet()) {

               sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");

           }

           url += sb.substring(0, sb.length() - 1);

       }

return get(url);

}

 

 

 

/**

* 执行get请求,返回String类型的请求

* @param url

* @return

* @throws IOException

* @throws HttpClientException

*/

public static String get(String url,Map<String,String> headers) throws IOException, HttpClientException {

CloseableHttpClient httpclient = createClient();

String body = null;

logger.info("create httpget:" + url);

HttpGet get = new HttpGet(url);

if (null != headers) {

for (String key : headers.keySet()) {

get.setHeader(key, headers.get(key));

}

}

try {

body = invoke(httpclient, get);

} catch (HttpClientException e) {

throw e;

} catch (UnknownHostException e) {

throw new HttpClientException(404);

} catch (Exception e) {

throw e;

} finally {

httpclient.close();

}

 

return body;

}

 

/**

* 执行get请求,返回String类型的请求

* @param url

* @return

* @throws IOException

* @throws HttpClientException

*/

public static String getAndCookie(String url,Map<String,String> headers,Map<String,String> cookieMap) throws IOException, HttpClientException {

CloseableHttpClient httpclient = createClient();

 

String body = null;

logger.info("create httpget:" + url);

HttpGet get = new HttpGet(url);

 

StringBuilder cookieStr = new StringBuilder(); 

if(null != cookieMap){

for(Entry<String, String> entry : cookieMap.entrySet()){

String name = entry.getKey();

String value = entry.getValue();

cookieStr.append(name).append('=').append(value).append(';');  

}

cookieStr.deleteCharAt(cookieStr.length() - 1);

}

if (null != headers) {

for (String key : headers.keySet()) {

get.setHeader(key, headers.get(key));

get.setHeader("Cookie", cookieStr.toString());

}

}

try {

body = invoke(httpclient, get);

} catch (HttpClientException e) {

throw e;

} catch (UnknownHostException e) {

throw new HttpClientException(404);

} catch (Exception e) {

throw e;

} finally {

httpclient.close();

}

 

return body;

}

 

/**

* 调用请求

* @param httpclient

* @param httpost

* @return

* @throws IOException

* @throws HttpClientException

*/

private static String invoke(CloseableHttpClient httpclient, HttpUriRequest httpost)

throws IOException, HttpClientException {

// 发送请求

CloseableHttpResponse response = sendRequest(httpclient, httpost);

/*String body = null;

try {

// 解析返回

body = paseResponse(response);

response.close();

} catch (HttpClientException e) {

e.printStackTrace();

} finally {

response.close();

}

return body;*/

 

return paseResponse(response);

}

 

/**

* 解析返回结果

* @param response

* @return

* @throws IOException

* @throws HttpClientException

*/

private static String paseResponse(HttpResponse response) throws IOException, HttpClientException {

logger.info("get response from http server..");

String body = null;

HttpEntity entity = response.getEntity();

logger.info("response status: " + response.getStatusLine());

// 获取状态码

int statusCode = response.getStatusLine().getStatusCode();

if (statusCode == 200) {

body = EntityUtils.toString(entity,"utf-8");

logger.info(body);

EntityUtils.consume(entity);

} else {

throw new HttpClientException(statusCode);

}

return body;

}

 

/**

* 发送请求

* @param httpclient

* @param httpost

* @return

* @throws IOException 

* @throws ClientProtocolException 

*/

private static CloseableHttpResponse sendRequest(CloseableHttpClient httpclient, HttpUriRequest httpost) throws ClientProtocolException, IOException {

 

CloseableHttpResponse response = httpclient.execute(httpost);

return response;

}

 

/**

* 构建HttpPost

* @param url

* @param params

* @return

*/

private static HttpPost postForm(String url, Map<String, String> headers, Map<String, String> params) {

 

HttpPost httpost = new HttpPost(url);

List<NameValuePair> nvps = new ArrayList<NameValuePair>();

 

Set<String> keySet = params.keySet();

for (String key : keySet) {

nvps.add(new BasicNameValuePair(key, params.get(key)));

}

 

if (null != headers) {

for (String key : headers.keySet()) {

httpost.setHeader(key, headers.get(key));

}

 

}

 

try {

 

logger.info("set utf-8 form entity to httppost");

httpost.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

 

return httpost;

}

 

/**

* @Title: doPost 

* @Description: json post提交

* @param url

* @param headers

* @param json

* @return    设定文件 

* JSONObject    返回类型 

* @throws 

* @author tianyunyun

* @date 2017年5月11日 上午10:35:09

*/

public static JSONObject doJsonPost(String url,Map<String, String> headers,JSONObject json){

        

        CloseableHttpClient httpclient = HttpClientBuilder.create().build();

        HttpPost post = new HttpPost(url);

        if (null != headers) {

for (String key : headers.keySet()) {

post.setHeader(key, headers.get(key));

}

 

}

        JSONObject response = null;

        try {

            StringEntity s = new StringEntity(json.toString(),"UTF-8");

            s.setContentEncoding("UTF-8");

            s.setContentType("application/json");//发送json数据需要设置contentType\

            post.setEntity(s);

            HttpResponse res = httpclient.execute(post);

            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){

                String result = EntityUtils.toString(res.getEntity());// 返回json格式:

                response = JSONObject.fromObject(result);

            }

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

        return response;

    }

 

/**

* @Title: doPost 

* @Description:  post提交

* @param url

* @param headers

* @param json

* @return    设定文件 

* JSONObject    返回类型 

* @throws 

* @author tianyunyun

* @date 2017年5月11日 上午10:35:09

*/

public static Map<String,Object> doPost(String url,Map<String, String> headers,String jsonStr){

        

        CloseableHttpClient httpclient = createClient();

        HttpPost post = new HttpPost(url);

        if (null != headers) {

for (String key : headers.keySet()) {

post.setHeader(key, headers.get(key));

}

 

}

        String result = null;

        Map<String,Object> resMap = null;

        try {

            StringEntity s = new StringEntity(jsonStr,"UTF-8");

            s.setContentEncoding("UTF-8");

            s.setContentType("application/x-www-form-urlencoded");

            post.setEntity(s);

            logger.info("========================执行请求==========================");

            HttpResponse res = httpclient.execute(post);

            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){

                result = EntityUtils.toString(res.getEntity());// 返回json格式:

            }

            if(result != null && result.length() > 0){

            resMap = JSON.parse(result, Map.class);

            }

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

        return resMap;

    }

public static void main(String[] args) {

String url = "http://localhost:8080/sound-haolei-android/house/selecthlhousetosyn";

String a = "";

Map<String,String> map = new HashMap<String,String>();

map.put("lastSyntime", "2017-08-10%2009%3A23%3A51");

try {

a = post(url, map);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (HttpClientException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.println(a);

}

}

 

 

 

 

 

 

 

 

 

 

 

 

package com.sound.cloudpos.base.util;

 

import java.io.File;

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

 

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

 

public class ProfileUtil {

private Logger log = LoggerFactory.getLogger("ProfileUtil.class");

 

private static class ProfileUtilHandler{

private static ProfileUtil instance = new ProfileUtil();

}

 

private ProfileUtil(){}

 

public static ProfileUtil getInstance(){

return ProfileUtilHandler.instance;

}

 

public String read(String filename, String key) {

 

String str = File.separator;

//非静态方法时使用:

//InputStream path = this.getClass().getResourceAsStream(".." + str + ".." + str+".."+str+".."+str+filename);

InputStream path = this.getClass().getResourceAsStream("/"+filename);

//InputStream path = ProfileUtil.class.getClass().getResourceAsStream(".." + str + ".." + str+".."+str+".."+str+"wx.properties");

 

Properties pros = new Properties();

try {

pros.load(path);

} catch (IOException ex) {

// System.out.println("file is not exist");

log.error("配置文件 "+filename+" 不存在!");

System.out.println("资源文件不存在");

}

 

String value = pros.getProperty(key);

 

return value;

}

}

 

分享到:
评论

相关推荐

    HttpClient IE插件破解版

    HttpClient是一款收费的IE插件(当然我上次的是一家破解后的,下载后直接可以安装使用) 主页提供对IE系列浏览器的HTTP请求监控,请求耗时等监控,是web前端开发人员不可缺少的一款好工具,利用这个工具可以分析出...

    httpclientUtil

    该项目其实有3个工具类: ...前2个工具类支持插件式配置Header、插件式配置httpclient对象,这样就可以方便地自定义header信息、配置ssl、配置proxy等。 第三个虽然支持代理、ssl,但是并没有把代理ssl等进行抽象。

    2015-9 httpclientdemo 2017.3.15 --谷歌浏览器插件【重要】

    描述中提到的“--谷歌浏览器插件【重要】”暗示这个项目可能包含了一个与谷歌浏览器(Google Chrome)相关的插件,这个插件可能使用了HttpClient库来与服务器进行通信。浏览器插件通常是由JavaScript、HTML和CSS编写...

    httpclient手册

    在编写Chrome插件时,HttpClient的这些知识点将帮助你高效地与服务器进行通信,无论是获取网页数据,还是发送用户交互信息。确保对HttpClient的深入了解和熟练使用,能提升插件的稳定性和用户体验。通过阅读...

    httpClient4.1入门教程.pdf

    此外,还提及了 HttpClient能够以插件式的自定义认证方案以及支持持久连接等高级功能。 在基础知识方面,文档首先讲解了环境的准备,包括下载HttpClient包并将其导入到工程中的具体步骤。随后介绍了几个主要的类,...

    c++ HttpClient 最新代码

    c++ HttpClient 最新代码c++ HttpClient 最新代码c++ HttpClient 最新代码c++ HttpClient 最新代码c++ HttpClient 最新代码c++ HttpClient 最新代码c++ HttpClient 最新代码c++ HttpClient 最新代码c++ HttpClient ...

    HttpClient4.5

    9. **可扩展性**:HttpClient的设计允许开发者通过插件和自定义策略来扩展其功能,满足特定需求。 10. **兼容性和稳定性**:HttpClient 4.5保持与早期版本的兼容性,使得升级过程更加平滑,减少了迁移成本。 在...

    【ASP.NET编程知识】.NET CORE HttpClient的使用方法.docx

    .NET CORE HttpClient 的使用方法 .NET CORE 中的 HttpClient 是一个非常重要的组件,它提供了一个强大且灵活的方式来发送 HTTP 请求。然而,在使用 HttpClient 时,我们需要注意一些重要的配置和使用方法,以避免...

    httpclient

    jsonp插件jsonp插件jsonp插件jsonp插件jsonp插件jsonp插件jsonp插件

    httpclient-3.1

    4. 可扩展性:通过插件机制,可以方便地扩展其功能,满足特定需求。 四、HttpClient 3.1的局限性与注意事项 1. 兼容性问题:HttpClient 3.1较旧,可能不支持最新的HTTP标准和特性,如HTTP/2。 2. 内存消耗:相比...

    HttpClient工具包

    10. **可扩展性**:HttpClient设计为模块化,开发者可以通过插件或自定义组件扩展其功能,比如添加新的HTTP方法、认证策略等。 在使用HttpClient时,需要注意以下几点: 1. **正确配置连接管理器**:合理的连接...

    HttpClient工具详细

    搜了一下网络上别人封装的HttpClient,大部分特别简单,有一些看起来比较高级...要做就做最好的,本工具类支持插件式配置Header、插件式配置httpclient对象,这样就可以方便地自定义header信息、配置ssl、配置proxy等。

    java httpClient 工具类 java httpClient 工具类

    java httpClient 工具类 java httpClient 工具类 java httpClient 工具类 java httpClient 工具类 java httpClient 工具类 java httpClient 工具类 java httpClient 工具类 java httpClient 工具类 java httpClient ...

    HttpClient 4.3教程.docx

    * 浏览器扩展:HttpClient可以用来实现浏览器扩展,例如浏览器插件。 结论 HttpClient是一个功能强大且灵活的HTTP客户端库,提供了一个功能丰富的HTTP客户端库,可以实现HTTP客户端的各种需求。它支持基本的HTTP...

    HttpClient以及获取页面内容应用

    压缩包中含有多个文档,从了解httpclient到应用。 httpClient 1httpClint 1.1简介 HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持...

    plugin-apache-httpclient-detect:用于检测apache httpclient类调用的插件

    apache httpclient检测插件 buildscript { repositories { jcenter() } dependencies { classpath "io.github.lizhangqu:plugin-apache-httpclient-detect:1.0.7" } } apply plugin: 'apache.httpclient....

    struts2 android httpclient 上传文件

    在Struts2中,文件上传主要依赖于`struts2-convention-plugin`和`struts2-core`的`CommonsFileUpload`插件。首先,你需要在Struts2配置文件中启用文件上传,然后创建一个Action类,该类包含一个`java.io.File`或`...

    httpclient3 自动登陆淘宝, 开心网

    7. **源码和工具**:标签中提到的“源码”可能意味着博客文章提供了相关的Java代码示例,而“工具”可能指的是HttpClient库本身或其他辅助工具,如用于分析网络请求的浏览器插件。 由于没有具体的博客内容,以上都...

    java httpclient 抓取 数据 和jar 包

    使用Maven的`assembly插件`或`shade插件`可以生成包含所有依赖的jar文件: 在pom.xml中添加以下配置: ```xml &lt;artifactId&gt;maven-assembly-plugin &lt;mainClass&gt;com.yourcompany.MainClass&lt;/mainClass&gt;...

    HttpClient4基础1--通过匿名代理访问网页

    同时,利用相关工具,如IDEA的插件或Maven、Gradle等构建工具,可以更方便地管理和依赖这些库。 总的来说,HttpClient4是Java开发者进行HTTP通信的强大工具,通过代理访问网页只是其众多功能之一。理解并熟练使用...

Global site tag (gtag.js) - Google Analytics