httpclient post请求没设有置编码的问题

某个网站要通过post请求来返回数值。

使用httpclient发送post请求的过程如下:

	public static void main(String[] args) throws ClientProtocolException, IOException
	{
		
		String url="http://localhost:8888/service/test?world=世界";
		
		HttpClient client=new DefaultHttpClient();
		
		
		HttpPost postMethod=new HttpPost(url);
		
		HttpResponse response=null;
		
		
		
		//添加内容要通过List<NameValuePair>,pairs要转换为HttpEntity对象.
		//这个pairs会被作为post参数传递过去
		List<NameValuePair> pairs=new ArrayList<NameValuePair>();
		
		pairs.add(new BasicNameValuePair("hello","你好"));
 
		
		//这里是重点,如果不设置编码,那么httpclient就会使用默认的iso8859,服务器端就无法得到正确的中文编码
		postMethod.setEntity(new UrlEncodedFormEntity(pairs));
		
		response=client.execute(postMethod);
		
		System.out.println(response.getStatusLine().getStatusCode());
		
		
	}



然后我们写一个Servlet,用来接受post请求。


@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
	{	
		
		
		
		
		String hello=req.getParameter("hello");
		
		System.out.println("hello= "+hello);
		
		
		String world=req.getParameter("world");
		
		System.out.println("world="+world);
		
	}



这里总共有两个参数, 一个是通过URL地址附带的参数,一个是放入了Httpclient对象中的参数。

通过测试, 前者被servlet正常显示, 但是后者显示为??


这里要打开httpclient的UrlEncodedFormEntity类,看一下源码:

     /**
     * Constructs a new {@link UrlEncodedFormEntity} with the list
     * of parameters in the specified encoding.
     *
     * @param parameters list of name/value pairs
     * @param encoding encoding the name/value pairs be encoded with
     * @throws UnsupportedEncodingException if the encoding isn't supported
     */
    public UrlEncodedFormEntity (
        final List <? extends NameValuePair> parameters,
        final String encoding) throws UnsupportedEncodingException {
        super(URLEncodedUtils.format(parameters, encoding), encoding);
        setContentType(URLEncodedUtils.CONTENT_TYPE + HTTP.CHARSET_PARAM +
                (encoding != null ? encoding : HTTP.DEFAULT_CONTENT_CHARSET));
    }

    /**
     * Constructs a new {@link UrlEncodedFormEntity} with the list
     * of parameters with the default encoding of {@link HTTP#DEFAULT_CONTENT_CHARSET}
     *
     * @param parameters list of name/value pairs
     * @throws UnsupportedEncodingException if the default encoding isn't supported
     */
    public UrlEncodedFormEntity (
        final List <? extends NameValuePair> parameters) throws UnsupportedEncodingException {
        this(parameters, HTTP.DEFAULT_CONTENT_CHARSET);
    }


可以看到, 最终要使用
URLEncodedUtils.format(paraneters,encoding)
由于我们没有传encoding进去, 程序会调用HTTP.DEFAULT_CONTENT_CHARSET,
而这个对象的值就是"ISO-8859-1"。


因此要想中文通过post请求参数传入后台,就必须设定参数的编码。
将上面的代码改为:


	postMethod.setEntity(new UrlEncodedFormEntity(pairs,"utf-8"));


问题就解决了
=============================


这里其实可以修改httpclient的源码,
找到org.apache.http.protocol.HTTP,


这里把DEFAULT_CONTENT_CHARSET修改为UTF_8即可。

猜你喜欢

转载自alleni123.iteye.com/blog/2074255