zoukankan      html  css  js  c++  java
  • HttpClient post封装

    /**
    * @title HttpUtils
    * @description post请求封装
    * @author maohuidong
    * @date 2017-12-18
    */
    public static class HttpUtils {


    /**
    * 定义编码格式 UTF-8
    */
    public static final String URL_PARAM_DECODECHARSET_UTF8 = "UTF-8";


    private static final String EMPTY = "";

    private static MultiThreadedHttpConnectionManager connectionManager = null;

    private static int connectionTimeOut = 25000;

    private static int socketTimeOut = 25000;

    private static int maxConnectionPerHost = 20;

    private static int maxTotalConnections = 20;

    private static HttpClient client;

    static{
    connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.getParams().setConnectionTimeout(connectionTimeOut);
    connectionManager.getParams().setSoTimeout(socketTimeOut);
    connectionManager.getParams().setDefaultMaxConnectionsPerHost(maxConnectionPerHost);
    connectionManager.getParams().setMaxTotalConnections(maxTotalConnections);
    client = new HttpClient(connectionManager);
    }

    /**
    * @function URLPost
    * @param
    * @description Post请求
    * @return 请求后的结果
    * @author maohuidong
    * @date 2017-12-18
    */
    public static String URLPost(String url, Map<String, String> params, String enc) throws UnsupportedEncodingException{
    String response = EMPTY;
    PostMethod postMethod = null;
    try {
    postMethod = new PostMethod(url);
    postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + enc);

    //将表单的值放入postMethod中
    Set<String> keySet = params.keySet();
    for(String key : keySet){
    String value = params.get(key);
    postMethod.addParameter(key, value);
    }
    //执行postMethod
    int statusCode = client.executeMethod(postMethod);
    if(statusCode == HttpStatus.SC_OK) {
    response = postMethod.getResponseBodyAsString();
    System.out.println(postMethod.getResponseCharSet());
    }
    }catch(HttpException e){
    e.printStackTrace();
    }catch(IOException e){
    e.printStackTrace();
    }finally{
    if(postMethod != null){
    postMethod.releaseConnection();
    postMethod = null;
    }
    }
    return response;
    }
    }

    Test:

    Map<String, String> map = new HashMap<String, String>();
    map.put("token", token);
    map.put("type", type);

    String result = HttpUtils.URLPost("http://localhost:8080/web_user_xxhzx/check_findUserInfo.action", map, "UTF-8");

    notice:

    如果返回乱码,需要转码:

    result = new  String(result.getBytes("ISO-8859-1"),"UTF-8");

    返回的编码可以通过postMethod.getResponseCharSet()获取到

  • 相关阅读:
    猴子选大王(约瑟夫环)
    centos 安装thrift
    KMP字符串匹配算法
    会话技术整理
    PHP数组整理版
    PHP基础知识6【系统内置函数--数组】
    PHP基础知识5【系统内置函数--字符串】
    PHP基础知识笔记4
    PHP基础知识笔记3
    PHP基础知识笔记2
  • 原文地址:https://www.cnblogs.com/maohuidong/p/8056121.html
Copyright © 2011-2022 走看看