`
conkeyn
  • 浏览: 1531381 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

HttpRequestClient

    博客分类:
  • Java
 
阅读更多

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);
        }
    }
}

 

分享到:
评论

相关推荐

    th2c:Tornado HTTP2客户端

    例子在协程中的用法可能是: from th2c import AsyncHTTP2Clientfrom tornado . httpclient import HTTPRequestclient = AsyncHTTP2Client ( host = 'nghttp2.org' , port = 443 , secure = True ,)request = ...

    Retrofit2.0 实现图文(参数+图片)上传方法总结

    在上面的示例中,我们创建了一个 `HttpRequestClient` 类,用于初始化 Retrofit 客户端。我们使用 `OkHttpClient` 创建了一个客户端,并添加了一个 log 拦截器用于日志显示。 三、上传文件 在使用 Retrofit2.0 ...

    Android getJSONObject与optJSONObject的区别结合源码分析

    JSONObject jsonObject = new JSONObject(HttpRequestClient.executeRequest(Constant.Url.GET_FOLLOW_GOODS_URL, param, true)); ResponseInfo responseInfo = new ResponseInfo(); try { if (jsonObject....

    ImageLoaderTask:使用内存缓存和OkHttp3加载图像的模块

    ImageLoaderTask 使用内存缓存和OkHttp3加载图像的模块还支持Get Request要求HttpRequestClient库可以包含在任何Android应用程序中。 HttpRequestClient库支持Android 4.4(Kitkat)及更高版本。在应用程序中使用...

    人力资源经理绩效考核表.xls

    人力资源经理绩效考核表

    智慧环卫管理平台建设方案Word(211页).docx

    一、智慧环卫管理平台的建设背景与目标 智慧环卫管理平台的建设源于对环卫管理全面升级的需求。当前,城管局已拥有139辆配备车载GPS系统、摄像头和油耗传感器的环卫车辆,但环卫人员尚未配备智能移动终端,公厕也缺乏信息化系统和智能终端设备。为了提升环卫作业效率、实现精细化管理并节省开支,智慧环卫管理平台应运而生。该平台旨在通过信息化技术和软硬件设备,如车载智能终端和环卫手机App,实时了解环卫人员、车辆的工作状态、信息和历史记录,使环卫作业管理透明化、精细化。同时,平台还期望通过数据模型搭建和数据研读,实现更合理的环卫动态资源配置,为环卫工作的科学、健康、持续发展提供决策支持。 二、智慧环卫管理平台的建设内容与功能 智慧环卫管理平台的建设内容包括运行机制体制建设、业务流程设计、智慧公厕系统建设、网络建设、主机和储存平台需求、平台运维管理体系、硬件标准规范体系以及考核评价体系等多个方面。其中,智慧公厕系统建设尤为关键,它能实时监控公厕运行状态,保障公厕的清洁和正常运行。平台建设还充分利用了现有的电子政务网络资源,并考虑了有线和无线网络的需求。在功能上,平台通过普查、整合等手段全面收集环卫车辆、企业、人员、设施、设备等数据,建立智慧环卫基础数据库。利用智能传感、卫星定位等技术实现环卫作业的在线监管和远程监控,实现对道路、公共场所等的作业状况和卫生状况的全面监管。此外,平台还建立了环卫作业网格化管理责任机制,实现从作业过程到结果的全面监管,科学评价区域、部门、单位和人员的作业效果。 三、智慧环卫管理平台的效益与风险规避 智慧环卫管理平台的建设将带来显著的环境、经济和管理效益。环境方面,它将有力推进环境卫生监管服务工作,改善环境卫生状况,为人民群众创造更加清洁、卫生的工作和生活环境。经济方面,通过智慧化监管,大大降低了传统管理手段的成本,提高了监管的准确性和效率。管理方面,平台能够追踪溯源市民反映的问题,如公厕异味、渣土车辆抛洒等,并找到相应的责任单位进行处置,防止类似事件再次发生。同时,平台还拥有强大的预警机制功能,能够在很多环卫问题尚未出现前进行处置。然而,平台建设也面临一定的风险,如部门协调、配合问题,建设单位选择风险以及不可预测的自然灾害等。为了规避这些风险,需要加强领导、统一思想,选择优秀的系统集成商承接项目建设,并做好计算机和应用系统的培训工作。同时,也要注意标准制定工作和相关法律法规的制定工作,以保证系统建设完成后能够真正为环卫管理工作带来便利。

    apache-parent-10-14.el7.x64-86.rpm.tar.gz

    1、文件内容:apache-parent-10-14.el7.rpm以及相关依赖 2、文件形式:tar.gz压缩包 3、安装指令: #Step1、解压 tar -zxvf /mnt/data/output/apache-parent-10-14.el7.tar.gz #Step2、进入解压后的目录,执行安装 sudo rpm -ivh *.rpm 4、安装指导:私信博主,全程指导安装

    用于卫星通信的CTS天线

    用于卫星通信的圆极化CTS天线研究

    人事档案登记及查询系统.xlsx

    人事档案登记及查询系统

    12 -防损部经理绩效考核表1.xlsx

    12 -防损部经理绩效考核表1

    泰尔指数模型stata全流程代码+数据+文献(数据权威)

    ## 一、泰尔指数模型stata全流程代码+数据+文献 参考C刊《农业经济问题》朱红根(2023)老师的做法,用泰尔指数是衡量个人或地区之间收入差距的重要指标,本文利用泰尔指数分析中国区域内和区域间数字乡村发展水平的差异,测算了全国总体差异、区域内差异、区域间差异以及相关贡献率。此资料包括stata全流程代码、案例数据、参考文献,用excel计算有标注有过程 ,并且参照文献讲的。 ## 二、2005-2021年城乡收入差距与泰尔指数:原始数据+测算结果 泰尔熵标准(Theil’s entropy measure)或者泰尔指数(Theil index)是衡量个人之间或者地区间收入差距(或者称不平等度)的指标。又称泰尔系数或锡尔指数,但我还是习惯叫泰尔指数。Theil指数用来表示区域经济差异状况,数值越大则差异程度越大。 数据名称:城乡收入差距与泰尔指数(原始数据+测算) 数据年份:2005-2021年 指标变量:泰尔指数、城镇收入占农村收入之比、城镇居民人均可支配收入、农村居民人均可支配收入、乡村人口、全体居民人均可支配收入、城镇人口、年末常住人口 测算公式:

    34 -配送部经理绩效考核表1.xlsx

    34 -配送部经理绩效考核表1

    [2024最新更新]全国城投公司数据大全(数据权威)

    1.资料名称:2021-1998年城投公司数据大全 2.数据指标:序号、公司名称、区域、城投评分、省内排名、最新主体评级、行政等级、 股东背景、股权关系、平台重要性、城投口径、实控人、 总资产(亿元)、 货币资金(亿元)、土地资产(亿元)、受限资产(亿元)、应收账款(亿元) 应收类款项政府占比(%)、营业收入(亿元)、公益性&准公益性主营占比(%)、归母净利润(亿元)、政府补助(亿元)、总资产报酬率(%)、有息债务(亿元)、 短期债务(亿元)、借款(亿元)、债券余额(亿元)、私募债占比(%)、 非标融资(亿元)、资产负债率(%)、债务资本化比率(%) 对外担保比例(%)、EBITDA/利息(倍)、EBITDA全部债务比(%)、授信余额(亿元)、 最新报告期 、申万行业 城投公司是城市建设投资公司的简称,是全国各大城市政府投资融资平台,起源于1991年,承担相应的政府职能,是特殊市场经营体。 此类城投公司大多是不具备盈利能力的,属于事业单位或者国有独资公司性质,他们是通过政府补贴的方式实现盈利,属于带有政府性质的特殊市场经营体。

    推广立方连通圈网络的Hamilton分解的算法.pdf

    推广立方连通圈网络的Hamilton分解的算法.pdf

    材料员绩效考核表.xls

    材料员绩效考核表

    2023年全国大学生英语竞赛样题(A类).pdf

    2023年全国大学生英语竞赛样题(A类)

    考虑柔性负荷的综合能源低碳经济调度模型研究:基于碳交易与场景分析的优化求解方法结合CPLEX的灵活求解方案 ,考虑柔性负荷的综合能源低碳经济调度 调度模型参考第一篇文献 碳交易模型参考第二篇 考虑三种

    考虑柔性负荷的综合能源低碳经济调度模型研究:基于碳交易与场景分析的优化求解方法结合CPLEX的灵活求解方案。,考虑柔性负荷的综合能源低碳经济调度 调度模型参考第一篇文献 碳交易模型参考第二篇 考虑三种场景并用cplex求解 场景一调度结果如图所示 本代码可改写能力强 ,核心关键词: 1. 柔性负荷综合能源低碳经济调度; 2. 调度模型; 3. 碳交易模型; 4. 场景分析; 5. Cplex求解; 6. 改写能力强。,"综合能源低碳调度:多场景Cplex求解的柔性负荷模型及优化结果展示"

    计算机网络技术考试题(含参考答案).doc

    计算机网络

    C语言刷题-lesson3.pdf

    C语言刷题-lesson3

    基于条件风险价值CVaR的微网动态定价与调度策略:主从博弈模型下的社会福利最大化与产消者合作博弈,MATLAB代码:基于条件风险价值CVaR的微网动态定价与调度策略 关键词:P2P交易 微网优化调度

    基于条件风险价值CVaR的微网动态定价与调度策略:主从博弈模型下的社会福利最大化与产消者合作博弈,MATLAB代码:基于条件风险价值CVaR的微网动态定价与调度策略 关键词:P2P交易 微网优化调度 条件风险价值 合作博弈 动态定价 仿真平台:MATLAB yalmip+cplex+mosek 主要内容:代码主要做的是一个基于主从博弈的考虑差别定价和风险管理的微网动态定价与调度策略,构建了双层能源管理框架,上层为零商的动态定价模型,目标是社会福利最大化;下层是多个产消者的合作博弈模型,优化各产消者的能量管理策略,各产消者之间可以进行P2P交易。 同时,采用纳什谈判法对多个产消者的合作剩余进行公平分配,还考虑了运行风险,采用条件风险价值(CVaR)随机规划方法来描述零商的预期损失。 代码非常精品,注释保姆级 ,基于CVaR的微网动态定价与调度策略:P2P交易下的风险管理及优化调度

Global site tag (gtag.js) - Google Analytics