关于httpclient 请求时,出现乱码问题
在用common-httpclient.jar,实现发生http请求时,出现了浏览器时不存在乱码问题,用代码实现时出现乱码问题,根据一般的解决方案就是一句请求报文头的方法像:
method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
但是还会出现乱码,仔细研究了浏览器http的请求,想到设置请求报文头的编码是为了在接入请求那边取参数这些不会乱码,返回时也存把内容从字节流转换为字符流的问题,也需要编码,这就需要在服务端返回时要设置返回编辑格式,
如果不设置就会使用默认的ISO-88951,因为服务器不设置也可以通过在请求时报文头里加上期望返回的编码格式,就是Accept参数
method.setRequestHeader("Accept", "text/plain;charset=utf-8");
/** * */ package com.powerjun.xxxxx.platform.util; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <pre> * http 请求工具类 * </pre> * * @author qinyujun qinyujun@powerjun.cn * @version 1.00.00 * * <pre> * 修改记录 * 修改后版本: 修改人: 修改日期: 修改内容: * </pre> */ public class HttpClientUtil { private static Logger logger = LoggerFactory .getLogger(HttpClientUtil.class); public static final String REQUEST_TYPE_POST = "post"; public static final String REQUEST_TYPE_GET = "get"; private static final String DEFAULT_CHARSET = "UTF-8"; public static final String RESPONSE_BODY = "responseBody"; public static final String COOKIES = "cookies"; public static byte[] doPost(String url, Map params) throws Exception{ Map result = doHttpRequest(url, params, REQUEST_TYPE_POST, DEFAULT_CHARSET); return (byte[]) result.get(RESPONSE_BODY); } public static Map doPostWithCookie(String url, Map params) throws Exception{ return doHttpRequest(url, params, REQUEST_TYPE_POST, DEFAULT_CHARSET); } public static Map doHttpRequest(String url, Map<String, String> params, String requestType, String charset) throws Exception { Map resultMap = new HashMap(); HttpClient httpClient = new HttpClient(); //连接超时时间 httpClient.getHttpConnectionManager().getParams() .setConnectionTimeout(15000); //读取超时时间 httpClient.getHttpConnectionManager().getParams().setSoTimeout(30000); PostMethod method = new PostMethod(url); try { method.setRequestBody(mapToNameValuePairs(params)); //设置请求报文头的编码 method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); //设置期望返回的报文头编码 method.setRequestHeader("Accept", "text/plain;charset=utf-8"); int statusCode = httpClient.executeMethod(method); httpClient.getState().getCookies(); resultMap.put(COOKIES, httpClient.getState().getCookies()); if (statusCode == HttpStatus.SC_OK) { resultMap.put("responseBody", method.getResponseBody()); } else if(statusCode == HttpStatus.SC_MOVED_TEMPORARILY){ Header locationHeader = method.getResponseHeader("location"); String location = locationHeader.getValue(); System.out.println("***redirect location "+location); logger.error("访问地址被重定向[{}],状态码[{}],参数[{}]", new Object[]{url, statusCode, params}); }else{ logger.error("访问地址失败[{}],状态码[{}],参数[{}]", new Object[]{url, statusCode, params}); } return resultMap; } catch (Exception e) { logger.error("http异常信息[{}][{}]" , url, e.getMessage()); throw e; } finally { method.releaseConnection(); //httpClient.getHttpConnectionManager().closeIdleConnections(0); } } private static NameValuePair[] mapToNameValuePairs(Map params) { if (params == null) { return new NameValuePair[]{}; } NameValuePair[] pairs = new NameValuePair[params.size()]; Set<Entry> entrys = params.entrySet(); int i = 0; for (Entry entry : entrys) { NameValuePair pair = new NameValuePair(); pair.setName((String) entry.getKey()); if (entry.getValue() instanceof String) { pair.setValue((String) entry.getValue()); } else if (entry.getValue() instanceof Number) { pair.setValue(String.valueOf(entry.getValue())); } pairs[i] = pair; i++; } return pairs; } public static String getCookieByName(Cookie[] cookies, String name, String path){ String result = null; if(cookies != null){ for(Cookie cookie : cookies){ if(name.equals(cookie.getName()) && path.equals(cookie.getPath())){ result = cookie.getValue(); break; } } } return result; } public static void main(String[] args) { try { Map<String, String> paramsMap = new HashMap<String, String>(); paramsMap.put("action", "xxxxx"); paramsMap.put("gnId", "xxxxxx"); paramsMap.put("ticket", "xxxxxxxx"); byte[] result = doPost("http://xxxxxxx.do", null); System.out.println(new String(result)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }