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

HttpRequestClient

程序员文章站 2022-07-07 16:57:56
...

http请求工具

public class WebConstant {

	// HTTP参数传递方式
	public final static int by_header = 1;
	public final static int by_params = 2;
}

 

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;


/**
 * 操作HttpServletRequest的参数(以后可能通过类似ServletRequestWrapper实现)
 *
 * @author ybbk
 * @date Jun 5, 2009 2:55:16 PM
 * @version 0.0.1-snapshot
 */
public class ParamUtils {

  /**
   * 对参数按字典升序排序 ,并且去掉不需要的参数<br>
   * 
   * @param params
   * @param ignoreParams
   * @return
   */
  public static Map<String, Object> sortParams(Map<String, Object> params,
          List<String> ignoreParams) {
    Collection<String> keyset = params.keySet();
    List<String> list = new ArrayList<String>(keyset);

    // 对key键值按字典升序排序
    Collections.sort(list);

    // 签名步骤一:按字典排序参数
    Map<String, Object> result = new TreeMap<String, Object>();
    for (Iterator<String> it = list.iterator(); it.hasNext();) {
      String key = it.next();
      if (ignoreParams != null && ignoreParams.contains(key)) {
        continue;
      }
      result.put(key, params.get(key));
    }

    return result;
  }

  /**
   * 作用:格式化参数, name=xx&age=xx
   * 
   * @param params
   * @param urlencode
   * @param escapeBlank 是否去掉值是空的参数
   * @return
   * @throws UnsupportedEncodingException
   */
  public static String formatParamMap(Map<String, Object> params, boolean needEncode,
          boolean escapeBlank, String charSet) throws UnsupportedEncodingException {

    StringBuilder sb = new StringBuilder();
    for (Iterator<String> it = params.keySet().iterator(); it.hasNext();) {
      String key = it.next();
      Object value = params.get(key);
      if (value == null && escapeBlank) {
        continue;
      } else {
        if (value instanceof String) {
          String str = (String) value;
          if (StringUtils.isBlank(str) && escapeBlank) {
            continue;
          } else {
            if (needEncode) {
              value = URLEncoder.encode(value + "", charSet);
            }
          }
        }
      }
      sb.append(key).append("=").append(value).append("&");
    }
    String result = sb.toString();
    if (result.length() > 0) {
      result = result.substring(0, result.length() - 1);
    }
    return result;
  }

  /**
   * 去掉空白的参数
   * 
   * @param params
   * @param needEncode
   * @param charSet
   * @return
   * @throws UnsupportedEncodingException
   */
  public static String formatParamMap(Map<String, Object> params, boolean needEncode,
          String charSet) throws UnsupportedEncodingException {

    return formatParamMap(params, needEncode, true, charSet);
  }

  /**
   * 模糊匹配某类参数值,如new-img-*
   * 
   * @param request
   * @param paramNamePrefix
   * @return
   */
  public static List<String> getValues(HttpServletRequest request, String paramNamePrefix) {
    Map requestParams = request.getParameterMap();
    List<String> results = new ArrayList<String>();
    for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
      String name = (String) iter.next();
      if (name.startsWith(paramNamePrefix)) {
        String[] values = (String[]) requestParams.get(name);
        for (String value : values) {
          results.add(value);
        }
      }
    }
    return results;

  }

  /**
   * 模糊匹配某类参数名称,如new-img-*
   * 
   * @return
   */
  public static List<String> getParamters(HttpServletRequest request, String paramNamePrefix) {
    Map requestParams = request.getParameterMap();
    List<String> params = new ArrayList<String>();
    for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
      String name = (String) iter.next();
      if (name.startsWith(paramNamePrefix)) {
        params.add(name);
      }
    }
    return params;
  }

  /**
   * 得到Http参数
   *
   * @param request HttpServletRequest
   * @param paramName 参数名
   * @param defaultStr 默认值
   * @return
   */
  public static String getString(HttpServletRequest request, String paramName, String defaultStr) {
    String value = request.getParameter(paramName);
    if (value == null) {
      return defaultStr;
    }
    return value.trim();
  }

  /**
   * 得到Http字符串数组参数
   *
   * @param request HttpServletRequest
   * @param paramName 参数名
   * @return
   */
  public static String[] getStringArray(HttpServletRequest request, String paramName) {
    return request.getParameterValues(paramName);
  }

  /**
   * 得到整形参数
   *
   * @param request HttpServletRequest
   * @param paramName 参数名
   * @param defaultInt 默认值
   * @return
   */
  public static Integer getInteger(HttpServletRequest request, String paramName, int defaultInt) {
    String value = request.getParameter(paramName);
    if (value == null) {
      return defaultInt;
    }
    try {
      return new Integer(value);
    } catch (NumberFormatException e) {
      return defaultInt;
    }
  }

  public static Integer[] getIntegerArray(HttpServletRequest request, String paramName) {
    String[] values = getStringArray(request, paramName);
    if (values == null) {
      return null;
    }
    List<Integer> list = new ArrayList<Integer>();
    for (String value : values) {
      try {
        Integer paramValue = new Integer(value);
        list.add(paramValue);
      } catch (NumberFormatException e) {
      }
    }
    return list.toArray(new Integer[] {});
  }

  public static Long getLong(HttpServletRequest request, String paramName, long defaultLong) {
    String value = request.getParameter(paramName);
    if (value == null) {
      return defaultLong;
    }
    try {
      return new Long(value);
    } catch (NumberFormatException e) {
      return defaultLong;
    }
  }

  public static Long[] getLongArray(HttpServletRequest request, String paramName) {
    String[] values = getStringArray(request, paramName);
    if (values == null) {
      return null;
    }
    List<Long> list = new ArrayList<Long>();
    for (String value : values) {
      try {
        Long paramValue = new Long(value);
        list.add(paramValue);
      } catch (NumberFormatException e) {
      }
    }
    return list.toArray(new Long[] {});
  }

  public static Double getDouble(HttpServletRequest request, String paramName,
          double defaultDouble) {
    String value = request.getParameter(paramName);
    if (value == null) {
      return defaultDouble;
    }
    try {
      return new Double(value);
    } catch (NumberFormatException e) {
      return defaultDouble;
    }
  }

  public static Double[] getDoubleArray(HttpServletRequest request, String paramName) {
    String[] values = getStringArray(request, paramName);
    if (values == null) {
      return null;
    }
    List<Double> list = new ArrayList<Double>();
    for (String value : values) {
      try {
        Double paramValue = new Double(value);
        list.add(paramValue);
      } catch (NumberFormatException e) {
      }
    }
    return list.toArray(new Double[] {});
  }

  /**
   * 把HttpServletRequest中所有的参数重新组织,形成新的查询字符串.用于转向页面时,保存request中的参数值不丢失
   *
   * @param request
   * @param encoding URL编码格式
   * @return 新的参数排除.格式是: aaa=value&bbb=value&
   */
  @SuppressWarnings("rawtypes")
  public static String getFullRequestUrl(HttpServletRequest request, String encoding) {
    StringBuffer sb = new StringBuffer();
    Map requestParams = request.getParameterMap();
    for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
      String name = (String) iter.next();
      String[] values = (String[]) requestParams.get(name);
      for (String value : values) {
        try {
          sb.append(name).append("=").append(java.net.URLEncoder.encode(value, encoding))
                  .append("&");
        } catch (UnsupportedEncodingException e) {
        }
      }
    }
    return sb.toString();
  }

  public static String getFullRequestUrl(String url, Map params, String ext, String encoding) {
    return getFullRequestUrl(url, params, ext, encoding, true, false);
  }

  /**
   * 将参数拼接到URL后面
   * 
   * @param url
   * @param params
   * @param ext 如#tip3
   * @param encoding
   * @param needEncode 是否需要编码
   * @param dropEmpty 去掉空的参数,如name=
   * @return
   */
  @SuppressWarnings("rawtypes")
  public static String getFullRequestUrl(String url, Map params, String ext, String encoding,
          boolean needEncode, boolean dropEmpty) {
    StringBuffer sb = new StringBuffer();
    for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
      String name = (String) iter.next();
      Object value = params.get(name);

      try {
        if (value == null) {
          if (dropEmpty) {
            continue;
          }
          sb.append(name).append("=&");
        } else {
          String str = value.toString();
          if (StringUtils.isBlank(str) && dropEmpty) {
            continue;
          }
          if (needEncode) {
            str = java.net.URLEncoder.encode(str, encoding);
          }
          sb.append(name).append("=").append(str).append("&");
        }
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
    }
    String requesturl = url + "?" + sb.toString();
    if (requesturl.lastIndexOf("&") != -1) {
      requesturl = requesturl.substring(0, requesturl.length() - 1);
    }

    if (StringUtils.isNotBlank(ext)) {
      requesturl = requesturl + ext;
    }
    return requesturl;
  }

  /**
   * 将参数拼接到URL后面,除了参数外,不带多余的#信息,默认使用utf8进行encode
   * 
   * @param url
   * @param params
   * @param ext
   * @param encoding
   * @return
   */
  @SuppressWarnings("rawtypes")
  public static String getFullRequestUrl(String url, Map params) {
    return getFullRequestUrl(url, params, "", "utf-8");
  }

  /**
   * 把HttpServletRequest中所有的参数重新组织,形成新的查询字符串.用于转向页面时,保存request中的参数值不丢失,默认utf-8 编码
   *
   * @param request
   * @return 新的参数排除.格式是: aaa=value&bbb=value&
   */
  public static String getFullRequestUrl(HttpServletRequest request) {
    return getFullRequestUrl(request, "utf-8");
  }

  /**
   * 得到当前的URL及所有参数,用于转向页面时,保存request中的参数值不丢失,默认utf-8编码
   *
   * @param request
   * @return 请求地址中,完整的URL和参数
   */
  public static String getRequestUrl(HttpServletRequest request) {
    String requesturl = request.getRequestURL().toString();
    String params = getFullRequestUrl(request);
    if (params.length() > 0) {
      requesturl = requesturl + "?" + params;
    }
    return requesturl;
  }

  /////////////////////////////////////////////////////////
  /**
   * @param request
   * @return
   */
  public static Map<String, String> parseFromHeader(HttpServletRequest request) {
    Map<String, String> params = new HashMap<String, String>();
    @SuppressWarnings("unchecked")
    Enumeration<String> e = request.getHeaderNames();
    while (e.hasMoreElements()) {
      String key = e.nextElement();
      params.put(key.toLowerCase(), request.getHeader(key));
    }
    return params;
  }

  /**
   * 请求参数组转换成Map
   */
  public static Map<String, String> parameterToMap(HttpServletRequest request) {
    Map<String, String> params = new HashMap<String, String>();
    @SuppressWarnings("unchecked")
    Enumeration<String> e = request.getParameterNames();
    while (e.hasMoreElements()) {
      String key = e.nextElement();
      params.put(key, request.getParameter(key));
    }
    return params;
  }

  /**
   * 请求参数组换成字符串, 格式为: key=value. 方便打印日志
   */
  public static String parameterToString(HttpServletRequest request) {
    StringBuffer sb = new StringBuffer();
    @SuppressWarnings("unchecked")
    Enumeration<String> e = request.getParameterNames();
    while (e.hasMoreElements()) {
      String key = e.nextElement();
      sb.append(key).append("=").append(request.getParameter(key)).append(" ");
    }
    return sb.toString();
  }

  /**
   * POST请求的BODY转化为String
   * 
   * @param request
   * @return
   * @throws IOException
   */
  public static String contentToString(HttpServletRequest request) throws IOException {
    try {
      java.io.BufferedReader reader =
              new java.io.BufferedReader(new java.io.InputStreamReader(request.getInputStream()));
      StringBuffer sb = new StringBuffer();
      String tmp = null;
      while ((tmp = reader.readLine()) != null) {
        sb.append(tmp).append("\r\n");
      }
      return sb.toString();
    } catch (IOException e) {
      throw e;
    }
  }

  /**
   * 请求参数表转转换. 转换规则为,参数名前加上"c_"以和数据库字段名一致. 重要规则: 数据库建表时, 接口字段统一为字符串型, 字段名为 c_参数名
   */
  public static void parserParameter(HttpServletRequest request, Map<String, Object> params,
          String[] parameterList) {
    for (String k : parameterList) {
      String v = ParamUtils.getString(request, k, "");
      params.put("c_".concat(k), v);
    }
  }

  /**
   * 请求参数表转转换. 传入二维数组,数组为: 参数名, 列名
   */
  public static void parserParameter(HttpServletRequest request, Map<String, Object> params,
          String[][] parameterList) {
    for (String[] k : parameterList) {
      String v = ParamUtils.getString(request, k[0], "");
      params.put(k[1], v);
    }
  }

  /**
   * 信息费转换
   * 
   * @param price 信息费 单位:分
   */
  public static BigDecimal getPrice(String price/* 信息费:单位:分 */) {
    BigDecimal amount = null;
    try {
      float fee = Float.parseFloat(price);
      amount = new BigDecimal(fee / 100);
    } catch (NumberFormatException e) {
      amount = null;
    }
    return amount;
  }

  /**
   * 转码转换
   * 
   * @param inputStr
   * @param srcEncoding
   * @param dstEncoding
   * @return
   */
  public static String encoding(String inputStr, String srcEncoding, String dstEncoding) {
    try {
      return new String(inputStr.getBytes(srcEncoding), dstEncoding);
    } catch (UnsupportedEncodingException e) {
    }
    return inputStr;
  }

  /**
   * 将参数从request封装到指定bean
   * 
   * @author: hejianhui@wegooooo.com
   * @param request
   * @param clazz
   * @return
   * @return: Object
   * @time: 2016年7月11日 下午4:05:43
   */
  @SuppressWarnings("rawtypes")
  public Object request2bean(HttpServletRequest request, Class clazz) {
    try {
      Field[] file = clazz.getDeclaredFields();
      Object obj = clazz.newInstance();
      for (int i = 0; i < file.length; i++) {
        String value = request.getParameter(file[i].getName());

        BeanUtils.setProperty(obj, file[i].getName(), value);
      }

      return obj;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }



}

 

 .

import com.google.gson.Gson;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.CharsetUtils;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;

/**
 * http请求工具
 */
@Slf4j
public class HttpRequestClient {

    public static class MyX509TrustManager implements TrustStrategy {
        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    }

    public static CloseableHttpClient createHttpClient(boolean enableSSL) throws Exception {
        try {
            if (enableSSL) {
                SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new MyX509TrustManager())
                        .build();
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
                return HttpClients.custom().setSSLSocketFactory(sslsf).build();
            } else {
                return HttpClients.createDefault();
            }
        } catch (Exception e) {
            throw e;
        }
    }

    public static String doPostText(String url, String text, boolean enableSSL) throws Exception {
        CloseableHttpClient httpclient = createHttpClient(enableSSL);

        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            httpPost.setEntity(new StringEntity(text, "utf-8"));

            response = httpclient.execute(httpPost);
            org.apache.http.HttpEntity entity = response.getEntity();

            if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {
                if (entity != null) {
                    String result = EntityUtils.toString(entity, "utf-8");
                    EntityUtils.consume(entity);
                    return result;
                } else {
                    return null;
                }
            }

            EntityUtils.consume(entity);
            return null;
        } catch (ClientProtocolException e) {
            throw new Exception(e);
        } catch (IOException e) {
            throw new Exception(e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                throw new Exception(e);
            }
        }
    }


    public static byte[] getBytes(String urlPath) throws Exception {
        InputStream inStream = getInputStream(urlPath);
        if (inStream != null) {
            return readStream(inStream);
        }
        return null;
    }

    private static byte[] readStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }

    public static InputStream getInputStream(String urlPath) throws IOException {
        URL url = new URL(urlPath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return conn.getInputStream();
        }
        return null;
    }

    public static void saveToFile(String urlPath, File saveFile)
            throws Exception {
        URL url = new URL(urlPath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStream is = conn.getInputStream();

            FileOutputStream fos = new FileOutputStream(saveFile);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            is.close();
            fos.close();
        }
    }

    public static String doGetByParams(String url, Map<String, Object> params)
            throws Exception {
        return doGet(WebConstant.by_params, url, params);
    }

    public static String doGetByHeader(String url, Map<String, Object> params)
            throws Exception {
        return doGet(WebConstant.by_header, url, params);
    }

    public static String doGet(int paramsPassMethod, String url,
                               Map<String, Object> params) throws Exception {
        return doGet(paramsPassMethod, url, params, false, null);
    }


    public static String doGet(int paramsPassMethod, String url,
                               Map<String, Object> params, boolean enableSSL, HttpClient client) throws Exception {
        return doGet(paramsPassMethod, url, params, enableSSL, client, "utf-8");
    }

    public static String doGet(int paramsPassMethod, String url,
                               Map<String, Object> params, boolean enableSSL, HttpClient client, String charset) throws Exception {
        log.info("doGet():url={};params={};", url, params);
        if (WebConstant.by_params != paramsPassMethod
                && WebConstant.by_header != paramsPassMethod) {
            throw new Exception("不支持的参数传递方式");
        }

        if (StringUtils.isEmpty(url)) {
            throw new Exception("URL为空");
        }

        if (WebConstant.by_params == paramsPassMethod) {

            if (params != null && !params.isEmpty()) {
                url = ParamUtils.getFullRequestUrl(url, params);
            }
        }

        CloseableHttpClient httpclient = null;
        if (client == null) {
            httpclient = createHttpClient(enableSSL);
        } else {
            httpclient = (CloseableHttpClient) client;
        }

        HttpGet httpGet = new HttpGet(url);

        if (WebConstant.by_header == paramsPassMethod) {
            if (params != null && !params.isEmpty()) {
                for (Iterator<String> it = params.keySet().iterator(); it
                        .hasNext(); ) {
                    String key = it.next();
                    String value = String.valueOf(params.get(key));
                    httpGet.setHeader(key, value);
                }
            }
        }

        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                if (entity != null) {
                    String result = EntityUtils.toString(entity, CharsetUtils.get(charset));  //20141205增加UTF-8
                    EntityUtils.consume(entity);
                    return result;
                } else {
                    return null;
                }
            }
        } catch (Exception e) {
            log.error("http请求接口异常:", e);
            throw new Exception(e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                throw new Exception(e);
            }
        }
        return null;
    }

    // ////////////////////////////////////////////////////////////////////////////////////////

    public static String doPostByParams(String url, Map<String, Object> params)
            throws Exception {
        return doPost(WebConstant.by_params, url, params);
    }

    public static String doPostByHeader(String url, Map<String, Object> params)
            throws Exception {
        return doPost(WebConstant.by_header, url, params);
    }

    public static String doPost(int paramsPassMethod, String url,
                                Map<String, Object> params) throws Exception {
        return doPost(paramsPassMethod, url, params, false, null);
    }

    public static String doPost(int paramsPassMethod, String url,
                                Map<String, Object> params, boolean enableSSL, HttpClient client) throws Exception {
        log.info("doPost():url={},params={}", url, params);

        if (WebConstant.by_params != paramsPassMethod
                && WebConstant.by_header != paramsPassMethod) {
            throw new Exception("不支持的参数传递方式");
        }

        if (StringUtils.isEmpty(url)) {
            throw new Exception("URL为空");
        }

        CloseableHttpClient httpclient = null;
        if (client == null) {
            httpclient = createHttpClient(enableSSL);
        } else {
            httpclient = (CloseableHttpClient) client;
        }

        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            if (WebConstant.by_params == paramsPassMethod) {

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                for (Iterator<String> it = params.keySet().iterator(); it
                        .hasNext(); ) {
                    String key = it.next();
                    Object obj = params.get(key);
                    if (obj != null) {
                        String value = String.valueOf(obj);
                        nameValuePairs.add(new BasicNameValuePair(key, value));
                    } else {
                        nameValuePairs.add(new BasicNameValuePair(key, null));
                    }
                }
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            }

            if (WebConstant.by_header == paramsPassMethod) {
                if (params != null && !params.isEmpty()) {
                    for (Iterator<String> it = params.keySet().iterator(); it
                            .hasNext(); ) {
                        String key = it.next();
                        String value = String.valueOf(params.get(key));
                        httpPost.setHeader(key, value);
                    }
                }
            }

            response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                if (entity != null) {
                    String result = EntityUtils.toString(entity, CharsetUtils.get("utf-8"));  //20141205增加UTF-8
                    EntityUtils.consume(entity);
                    return result;
                } else {
                    return null;
                }
            }

            EntityUtils.consume(entity);
            return null;
        } catch (ClientProtocolException e) {
            throw e;
        } catch (IOException e) {
            throw e;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                throw e;
            }
        }
    }

    public static String doPost(String url, Map<String, Object> headers,
                                Map<String, Object> params, boolean enableSSL, HttpClient client) throws Exception {
        log.info("doPost():url={},headers={},params={}", url, headers, params);
        if (StringUtils.isEmpty(url)) {
            throw new IllegalArgumentException("URL为空");
        }

        CloseableHttpClient httpclient = null;
        if (client == null) {
            httpclient = createHttpClient(enableSSL);
        } else {
            httpclient = (CloseableHttpClient) client;
        }

        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            if (!CollectionUtils.isEmpty(headers)) {
                if (headers != null && !headers.isEmpty()) {
                    for (Iterator<String> it = headers.keySet().iterator(); it
                            .hasNext(); ) {
                        String key = it.next();
                        String value = String.valueOf(headers.get(key));
                        httpPost.setHeader(key, value);
                    }
                }
            }
            if (!CollectionUtils.isEmpty(params)) {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                for (Iterator<String> it = params.keySet().iterator(); it
                        .hasNext(); ) {
                    String key = it.next();
                    Object obj = params.get(key);
                    if (obj != null) {
                        String value = String.valueOf(obj);
                        nameValuePairs.add(new BasicNameValuePair(key, value));
                    } else {
                        nameValuePairs.add(new BasicNameValuePair(key, null));
                    }
                }
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            }
            response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity, CharsetUtils.get("utf-8"));  //20141205增加UTF-8
                EntityUtils.consume(entity);
                return result;
            } else {
                EntityUtils.consume(entity);
                return null;
            }
        } catch (ClientProtocolException e) {
            throw e;
        } catch (IOException e) {
            throw e;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                throw e;
            }
        }
    }

    /**
     * 使用post方式提交json数据<br>
     * 并将返回的信息也进行json格式化
     */
    public static Map<String, Object> postJson(String url, Map<String, Object> params) throws Exception {
        Gson gson = new Gson();
        String json = gson.toJson(params);
        String resp = doPostText(url, json, true);
        log.info("resp:{}", resp);
        if (StringUtils.isNotBlank(resp)) {
            Map<String, Object> dataMap = gson.fromJson(resp, Map.class);
            if (dataMap == null) {
                return new HashMap<String, Object>();
            }
            return dataMap;
        }
        return new HashMap<String, Object>();
    }
}

 测试

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

public class CreateUserTest {

    @Test
    public void createUserTest() throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        String userId="5af2aebb478d200e400ec4d4";
        paramMap.put("username", userId);
        paramMap.put("password", "123456");
        Map<String, Object> headerMap = new HashMap<String, Object>();
        headerMap.put("Content-Type", "application/x-www-form-urlencoded");
        headerMap.put("Authorization", String.format("Basic %s", "dG9vX3VzZXJfcHJvZDo5OTk5OTk="));
        String result = HttpRequestClient.doPost( "https://xx.dd.cn/oauth/user", headerMap, paramMap, true, null);
        if (StringUtils.isBlank(result) || (result.indexOf("ok") == -1&& result.indexOf("duplicated") == -1)  ) {
            throw new IllegalStateException("创建Oauth2用户失败。userid: " + userId);
        }
    }
}

 

推荐阅读