欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-06 13:31:40
废话不多说,直接上代码 import java.io.ioexception; import java.io.unsupportedencodingexcept...

废话不多说,直接上代码

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请求工具类(实例讲解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。