关于HttpClient4.3.*的Post和Get提交乱码问题

无语了都,整了好久,网上各种答案,几乎都是不行的,在apache的官网和一件网友的资料,现在OK了,分享如下:

这个原因是服务器导致的,服务器比如tomcat接收get方法默认使用的是ISO-8859-1编码,而浏览器发送时文字编码是和页面编码保持一致的,如果页面是使用utf-8 编码 get方法文字自然是使用utf-8编码,但接收服务器没有设置的情况下用了ISO-8859-1编码接收,中文自然就成乱码了,不过由于ISO-8859-1编码是单字节编码所以我们可以使用getBytes("ISO-8859-1"),"utf-8"这样把文字重新转换成utf-8 编码。
第一个发送的文字是utf-8编码 而tomcat接收后用错误的ISO-8859-1编码了,这样getBytes("ISO-8859-1")后会重新得到正确的utf-8编码的字节数组 ,然后用 new 
String(request.getParameter("something").getBytes("ISO-8859-1"),"utf-8")重新将字节编码成UTF-8编码的文字这样文字就正确了。

如果是tomcat的话 server.xml文件里
<Connector port="80" protocol="HTTP/1.1"
 connectionTimeout="20000"  redirectPort="8443" URIEncoding="UTF-8"/>
后边的URIEncoding就是设置get方法编码的如果没有指定URL接收的编码类型,自动会用ISO-8859-1编码

示例代码如下:

/*
 * ====================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */

package test;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
 * This example demonstrates how to abort an HTTP method before its normal completion.
 */
public class ClientAbortMethod {

    public final static void main(String[] args) throws Exception {
    	 //post();
    		get();
    }
    
    public static void get()
    {
    	 CloseableHttpClient httpclient = HttpClients.createDefault();
         try {
         	String strUrl = "http://127.0.0.1:8080/Test/servlet/GetTest?info=";
         	String strParam = URLEncoder.encode("你好", "utf-8");
         	strUrl += strParam;
         	HttpGet httpget = new HttpGet(strUrl);
             System.out.println("Executing request " + httpget.getURI());
             CloseableHttpResponse response = httpclient.execute(httpget);
             try {
             	String strInfo = EntityUtils.toString(response.getEntity());
             	System.out.println(strInfo);
                 httpget.abort();
             } finally {
                 response.close();
             }
         } catch(Exception e)
         {
        	 e.printStackTrace();
         }
         finally {
             try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
         }
    }
    public static void post()
    {
    	try {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpResponse response;
			HttpEntity entity;
			HttpPost httpost = new HttpPost("http://127.0.0.1:8080/Test/servlet/GetTest");
			List <NameValuePair> nvps = new ArrayList <NameValuePair>();
			nvps.add(new BasicNameValuePair("info", "kaxu中文"));
			nvps.add(new BasicNameValuePair("password", "kaxu"));
			httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
			response = httpclient.execute(httpost);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

}


服务端的代码如下:

package com.neusoft;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetTest extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");

		PrintWriter out = response.getWriter();
		String info = new String(request.getParameter("info").getBytes("ISO-8859-1"),"utf-8");
		System.out.println(info);
		
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		request.setCharacterEncoding("utf-8");
		String strInfo = request.getParameter("info");
		String str1 = URLDecoder.decode(strInfo, "utf-8");
		System.out.println(str1);
		
		out.flush();
		out.close();
	}

}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值