/**
* @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()获取到