HttpClient4.5.2调用示例(转载+原创)

操作HttpClient时的一个工具类,使用是HttpClient4.5.2

package com.xxxx.charactercheck.utils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
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;

public class HttpClientUtil {
	private RequestConfig requestConfig = RequestConfig.custom()
		.setSocketTimeout(15000)
		.setConnectTimeout(15000)
		.setConnectionRequestTimeout(15000)
		.build();

	private static HttpClientUtil instance = null;
    private HttpClientUtil(){}
    public static HttpClientUtil getInstance(){
        if (instance == null) {
            instance = new HttpClientUtil();
        }
        return instance;
    }  

    /**
     * 发送 post请求
     * @param httpUrl 地址
     */
    public String sendHttpPost(String httpUrl) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        return sendHttpPost(httpPost);
    }  

    /**
     * 发送 post请求
     * @param httpUrl 地址
     * @param params 参数(格式:key1=value1&key2=value2)
     */
    public String sendHttpPost(String httpUrl, String params) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        try {
            //设置参数
            StringEntity stringEntity = new StringEntity(params, "UTF-8");
            stringEntity.setContentType("application/x-www-form-urlencoded");
            httpPost.setEntity(stringEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendHttpPost(httpPost);
    }  

    /**
     * 发送 post请求
     * @param httpUrl 地址
     * @param maps 参数
     */
    public String sendHttpPost(String httpUrl, Map<String, String> maps) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        // 创建参数队列
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        for (String key : maps.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendHttpPost(httpPost);
    }  

    /**
     * 发送 post请求(带文件)
     * @param httpUrl 地址
     * @param maps 参数
     * @param fileLists 附件
     */
    public String sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
        for (String key : maps.keySet()) {
            meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));
        }
        for(File file : fileLists) {
            FileBody fileBody = new FileBody(file);
            meBuilder.addPart("files", fileBody);
        }
        HttpEntity reqEntity = meBuilder.build();
        httpPost.setEntity(reqEntity);
        return sendHttpPost(httpPost);
    }  

    /**
     * 发送Post请求
     * @param httpPost
     * @return
     */
    private String sendHttpPost(HttpPost httpPost) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            // 创建默认的httpClient实例.
            httpClient = HttpClients.createDefault();
            httpPost.setConfig(requestConfig);
            // 执行请求
            response = httpClient.execute(httpPost);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接,释放资源
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }  

    /**
     * 发送 get请求
     * @param httpUrl
     */
    public String sendHttpGet(String httpUrl) {
        HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
        return sendHttpGet(httpGet);
    }  

    /**
     * 发送 get请求Https
     * @param httpUrl
     */
    public String sendHttpsGet(String httpUrl) {
        HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
        return sendHttpsGet(httpGet);
    }  

    /**
     * 发送Get请求
     * @param httpPost
     * @return
     */
    private String sendHttpGet(HttpGet httpGet) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            // 创建默认的httpClient实例.
            httpClient = HttpClients.createDefault();
            httpGet.setConfig(requestConfig);
            // 执行请求
            response = httpClient.execute(httpGet);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接,释放资源
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }  

    /**
     * 发送Get请求Https
     * @param httpPost
     * @return
     */
    private String sendHttpsGet(HttpGet httpGet) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            // 创建默认的httpClient实例.
            PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));
            DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
            httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
            httpGet.setConfig(requestConfig);
            // 执行请求
            response = httpClient.execute(httpGet);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接,释放资源
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }
}

调用例子

@ResponseBody
	@RequestMapping(value = "/check")
	public String check(
			Model model,
			HttpServletRequest request,
			HttpServletResponse response,
			String content) {
		try {
			String httpUrl = ExtendedServerConfig.getInstance().getStringProperty("httpUrl");
			Map<String, String> maps = new HashMap<String, String>();
			maps.put("content", content);
			maps.put("reserve_tag", ExtendedServerConfig.getInstance().getStringProperty("reserve_tag"));
			maps.put("user_key", ExtendedServerConfig.getInstance().getStringProperty("user_key"));
			maps.put("check_level", ExtendedServerConfig.getInstance().getStringProperty("check_level"));
			return HttpClientUtil.getInstance().sendHttpPost(httpUrl, maps);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
时间: 2024-12-23 22:43:01

HttpClient4.5.2调用示例(转载+原创)的相关文章

AndroidHttpClient详解及调用示例_Android

下面给大家展示了AndroidHttpClient结构: public final class AndroidHttpClient extends Object implements HttpClient 前言: 这类其实是Google对阿帕奇的HttpClient的一个封装,一些默认属性有android做了一些优化. 然后阿帕奇的HttpClient是对java中HttpUrlConnection的一个封装,感觉阿帕奇封装的还是不错的, 特别是其中的HttpEntity,很强大也很好用,能在a

jsp页面获取服务器时间的简单调用示例

 这篇文章主要介绍了jsp页面如何获取服务器时间及简单的调用示例,需要的朋友可以参考下       Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day= c.get(Calendar.DAY); 这三行加在<% %>里面 调用时用<%= year %><%= month%><%= day%&g

javascript间隔调用和延时调用示例

 这篇文章主要介绍了javascript间隔调用和延时调用示例,介绍setInterval方法和clearInterval方法的使用方法,大家参考使用吧 用setInterval方法可以以指定的间隔实现循环调用函数,直到clearInterval方法取消循环   用clearInterval方法取消循环时,必须将setInterval方法的调用赋值给一个变量,然后clearInterval方法引用该变量.    代码如下: <script type="text/javascript&quo

阿里大鱼ASP调用示例

阿里大鱼ASP调用示例 本demo地址:https://github.com/woodsrong/alidayu-asp-demo 本demo参考nodejs demo完成 重点可参考sign的生成方法 注意: 本demo短信签名暂时只支持4个以内汉字,待优化(目前JSONObject对象添加超过4个汉字报错) 代码示例 <!--#include file="alidayu-sdk/index.asp"--> <% '调用阿里大鱼SDK发送短信示例 Response.

用Java实现全国天气预报的api接口调用示例_java

step1:选择本文所示例的接口"全国天气预报接口" 聚合数据url:http://www.juhe.cn/docs/api/id/39/aid/87 step2:每个接口都需要传入一个参数key,相当于用户的令牌,所以第一步你需要申请一个key. step3:学过java的同学们都知道,当我们对一个类或者方法不明白其意图和思想时,我们可以去查看文档,这里也不例外,而且对于英文不是特别好的同学来说很幸运的是,聚合网站上的文档都是中文版本的,比起阅读java源码里的英文文档应该轻松很多.

帮忙写个API声明用调用示例

问题描述 一个wince系统采集器开发接口,非得要用.net做开发没办法,只能开始vb.net处女作dll是C++的,是个动态连接库发出2个函数,麻烦各位写个声明及调用示例用参考,感激不尽DeviceAPI.dll函数说明:1.intHardwareVersion_Ex(UINT8*pszData);功能:获取硬件版本号:参数:UINT8*pszData版本号信息:返回:0成功:其他失败:2.voidStartShake(intiTime);功能:设置震动器:参数:intiTime震动时间(单位

AndroidHttpClient详解及调用示例

下面给大家展示了AndroidHttpClient结构: public final class AndroidHttpClient extends Object implements HttpClient 前言: 这类其实是Google对阿帕奇的HttpClient的一个封装,一些默认属性有android做了一些优化. 然后阿帕奇的HttpClient是对java中HttpUrlConnection的一个封装,感觉阿帕奇封装的还是不错的, 特别是其中的HttpEntity,很强大也很好用,能在a

Android AIDL和远程Service调用示例代码_Android

Android:AIDL和远程Service调用 本讲的内容,理解起来很难,也许你看了很多资料也看不明白,但是用起来缺简单的要命.所以我们干脆拿一个音乐播放器中进度条的实例来说明一下AIDL和Remote Service的价值和使用方法,你把这个例子跑一边,体会一下就OK了.下面的例子是我 正在准备的项目实例中的一部分. 首先说明一下我们面临的问题,如果看不懂下面的描述请看前面的课程: 第一.我们知道在AndroId中如果需要进行音乐播放,最方面的方法就是使用自带的MediaPlayer对象,如

需要安全认证的远程EJB调用示例(Jboss EAP 6.2环境)

一,Remote EJB 服务接口定义: 1 package yjmyzz.ejb.server.helloworld; 2 3 public interface HelloWorldService { 4 5 public String sayHello(String name); 6 7 } 实现: 1 package yjmyzz.ejb.server.helloworld; 2 3 import javax.annotation.security.RolesAllowed; 4 impo