HttpUtils 发送http请求工具类(实例讲解)

废话不多说,直接上代码

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
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.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.pingan.qhcs.map.audit.constant.CodeConstant;
import com.pingan.qhcs.map.audit.exception.MapException;

public class HttpClientUtil {

 protected static Log logger = LogFactory.getLog(HttpClientUtil.class);

 private static PoolingHttpClientConnectionManager cm;
 private static String EMPTY_STR = "";
 private static String UTF_8 = "UTF-8";

 private static void init() {
  if (cm == null) {
   cm = new PoolingHttpClientConnectionManager();
   cm.setMaxTotal(50);// 整个连接池最大连接数
   cm.setDefaultMaxPerRoute(5);// 每路由最大连接数,默认值是2
  }
 }

 /**
  * 通过连接池获取HttpClient
  *
  * @return
  */
 public static CloseableHttpClient getHttpClient() {
  init();
  return HttpClients.custom().setConnectionManager(cm).build();
 }

 public static String httpGetRequest(String url) {
  HttpGet httpGet = new HttpGet(url);
  return getResult(httpGet);
 }

 public static String httpGetRequest(String url, Map<String, Object> params) throws URISyntaxException {
  URIBuilder ub = new URIBuilder();
  ub.setPath(url);

  ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
  ub.setParameters(pairs);

  HttpGet httpGet = new HttpGet(ub.build());

  return getResult(httpGet);
 }

 public static String httpGetRequest(String url, Map<String, Object> headers, Map<String, Object> params)
   throws URISyntaxException {
  URIBuilder ub = new URIBuilder();
  ub.setPath(url);

  ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
  ub.setParameters(pairs);

  HttpGet httpGet = new HttpGet(ub.build());
  for (Map.Entry<String, Object> param : headers.entrySet()) {
   httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
  }
  return getResult(httpGet);
 }

 public static String httpPostRequest(String url) {
  HttpPost httpPost = new HttpPost(url);
  return getResult(httpPost);
 }

 public static String httpPostRequest(String url, Map<String, Object> params) throws UnsupportedEncodingException {
  HttpPost httpPost = new HttpPost(url);
  ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
  httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
  return getResult(httpPost);
 }

 public static String httpPostRequest(String url, Map<String, Object> headers, Map<String, Object> params)
   throws UnsupportedEncodingException {
  HttpPost httpPost = new HttpPost(url);

  for (Map.Entry<String, Object> param : headers.entrySet()) {
   httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
  }

  ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
  httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));

  return getResult(httpPost);
 }

 public static String httpPostRequest(String url, Map<String, Object> headers, String strBody)
   throws Exception {
  HttpPost httpPost = new HttpPost(url);

  for (Map.Entry<String, Object> param : headers.entrySet()) {
   httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
  }
  httpPost.setEntity(new StringEntity(strBody, UTF_8));
  return getResult(httpPost);
 }

 private static ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) {
  ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
  for (Map.Entry<String, Object> param : params.entrySet()) {
   pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
  }

  return pairs;
 }

 /**
  * 处理Http请求
  *
  * setConnectTimeout:设置连接超时时间,单位毫秒。
  * setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
  * setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
  *
  * @param request
  * @return
  */
 private static String getResult(HttpRequestBase request) {

  RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000)
    .setConnectionRequestTimeout(5000).setSocketTimeout(60000).build();
  request.setConfig(requestConfig);// 设置请求和传输超时时间

  // CloseableHttpClient httpClient = HttpClients.createDefault();
  CloseableHttpClient httpClient = getHttpClient();
  try {
   CloseableHttpResponse response = httpClient.execute(request); //执行请求
   // response.getStatusLine().getStatusCode();
   HttpEntity entity = response.getEntity();
   if (entity != null) {
    // long len = entity.getContentLength();// -1 表示长度未知
    String result = EntityUtils.toString(entity);
    response.close();
    // httpClient.close();
    return result;
   }
  } catch (ClientProtocolException e) {
   logger.error("[maperror] HttpClientUtil ClientProtocolException : " + e.getMessage());
   throw new MapException(CodeConstant.CODE_CONNECT_FAIL, "HttpClientUtil ClientProtocolException :" + e.getMessage());
  } catch (IOException e) {
   logger.error("[maperror] HttpClientUtil IOException : " + e.getMessage());
   throw new MapException(CodeConstant.CODE_CONNECT_FAIL, "HttpClientUtil IOException :" + e.getMessage());
  } finally {

  }
  return EMPTY_STR;
 }

}

以上这篇HttpUtils 发送http请求工具类(实例讲解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • java发送http get请求的两种方法(总结)

    长话短说,废话不说 一.第一种方式,通过HttpClient方式,代码如下: public static String httpGet(String url, String charset) throws HttpException, IOException { String json = null; HttpGet httpGet = new HttpGet(); // 设置参数 try { httpGet.setURI(new URI(url)); } catch (URISyntaxExc

  • java发送HttpClient请求及接收请求结果过程的简单实例

    一. 1.写一个HttpRequestUtils工具类,包括post请求和get请求 package com.brainlong.framework.util.httpclient; import net.sf.json.JSONObject; import org.apache.commons.httpclient.HttpStatus; import org.apache.http.HttpResponse; import org.apache.http.client.methods.Htt

  • java实现http请求工具类示例

    通过http rest请求返回数据 复制代码 代码如下: import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import

  • HttpUtils 发送http请求工具类(实例讲解)

    废话不多说,直接上代码 import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFac

  • Java编写超时工具类实例讲解

    我们在开发过程中,在进行时间操作时,如果在规定的时间内完成处理的话,有可能会回到正确的结果.否则,就会被视为超时任务.此时,我们不再等待(不再执行)的时间操作,直接向调用者传达这个任务需要时间,被取消了. 1.说明 java已经为我们提供了解决办法.jdk1.5带来的并发库Future类可以满足这一需求.Future类中重要的方法有get()和cancel().get()获取数据对象,如果数据没有加载,则在获取数据之前堵塞,cancel()取消数据加载.另一个get(timeout)操作表明,如

  • C#实现的UDP收发请求工具类实例

    本文实例讲述了C#实现的UDP收发请求工具类.分享给大家供大家参考,具体如下: 初始化: ListeningPort = int.Parse(ConfigurationManager.AppSettings["ListeningPort"]); SendingPort = int.Parse(ConfigurationManager.AppSettings["SendingPort"]); SendingIp = ConfigurationManager.AppSe

  • Android快速开发系列 10个常用工具类实例代码详解

    打开大家手上的项目,基本都会有一大批的辅助类,今天特此整理出10个基本每个项目中都会使用的工具类,用于快速开发~~在此感谢群里给我发项目中工具类的兄弟/姐妹~ 1.日志工具类L.java package com.zhy.utils; import android.util.Log; /** * Log统一管理类 * * * */ public class L { private L() { /* cannot be instantiated */ throw new UnsupportedOpe

  • Android编程实现的身份证、车牌号正则验证工具类实例

    本文实例讲述了Android编程实现的身份证.车牌号正则验证工具类.分享给大家供大家参考,具体如下: /** * 正则表达式验证工具类(验证身份证.车牌号等) * * @author chenlin * */ public class ValidateUtil { /** * 验证str是否为正确的身份证格式 * * @param str * @return */ public static boolean isIdentityCard(EditText view) { boolean flag

  • Java语言描述MD5加密工具类实例代码

    编程中经常有用到MD5加密的情况,Java语言并没有像PHP一样提供原生的MD5加密字符串的函数,需要MD5加密的时候,往往需要自己写. 代码如下: import java.security.MessageDigest; public class MD5 { //公盐 private static final String PUBLIC_SALT = "demo" ; //十六进制下数字到字符的映射数组 private final static String[] hexDigits =

  • Android常用正则表达式验证工具类(实例代码)

    东西不多,但一般项目够用了. public class RegularUtil { //身份证 public static final String REGEX_ID_CARD = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$"; //验证邮箱 public static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\

  • js判断用户是输入的地址请求的路径(实例讲解)

    如下所示: /** * 如果是直接输入url访问的则刷新页面(防止缓存页面)针对Chrome,其他浏览器刷新referrer始终会为空,所以给个随机路径访问就加载不到缓存了. */ var userAgent = navigator.userAgent; // 获得浏览器的userAgent字符串 if(userAgent.indexOf("Chrome") > -1) { if(document.referrer == "") { document.loca

  • Nodejs 发布自己的npm包并制作成命令行工具的实例讲解

    <span style="font-family:Arial, Helvetica, sans-serif;background-color:rgb(255,255,255);">近日当我在使用npm上已经存在的一个包时,发现它有bug:于是决定自己实现这个功能,自己写一个npm包.</span> 下面我记录一下自己的实现过程. 1. npm init 选择一个文件夹,然后用命令行cd进去,然后执行npm init,这时会生成一长串表单,根据自己的实际情况填写内

  • Spring常用一些工具类实例汇总

    一.内置Resource类型 org.springframework.core.io.UrlResource org.springframework.core.io.ClassPathResource:以类路径的方式进行访问 org.springframework.core.io.FileSystemResource:以文件系统绝对路径的方式进行访问 org.springframework.web.context.support.ServletContextResource:以相对于 Web 应

随机推荐