`

HttpClient请求中文乱码详解

    博客分类:
  • J2SE
阅读更多
HttpClient 请求的中文乱码问题
相关类库:
commons-codec-1.3.jar,commons-httpclient-3.1.jar,commons-logging-1.1.1.jar

使用方法setContentCharset();
这里以GetMethod为例:
如果请求的页面编码为GB2312
其它部分略
GetMethod getMethod = new GetMethod("http://www.baidu.com");
//设置页面编码
getMethod.getParams().setContentCharset("GB2312");

基本上设置请求部分完成了
下面是对请求的页面读取的解析
最简单的方式是直接输出页面,这里基本上不需要任何设置。
System.out.println(getMethod.getResponseBodyAsString());

当然你也可以使用流方式读取
InputStream in = getMethod.getResponseBodyAsStream();
//这里的编码规则要与上面的相对应
BufferedReader br = new BufferedReader(new InputStreamReader(in,"GB2312"));
String tempbf;
StringBuffer html = new StringBuffer(100);
while ((tempbf = br.readLine()) != null) {
	html.append(tempbf +"\n");
}
System.out.println(html.toString());

当然还可以使用这样的方式,因为默认是使用ISO-8859-1,无非就是多进行了几次转码
InputStream in = getMethod.getResponseBodyAsStream();
//这里使用8859-1读取
BufferedReader br = new BufferedReader(new InputStreamReader(in,"ISO-8859-1"));
String tempbf;
StringBuffer html = new StringBuffer(100);
while ((tempbf = br.readLine()) != null) {
	html.append(tempbf +"\n");
}
//将8859-1再次转成GB2312
System.out.println(new String(html.toString().getBytes("ISO-8859-1"),"GB2312"));

我还是建议使用第一种方法,但我认为本质上是一致的
对于请求部分还可以通过如下几种方式进行设置
getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"GB2312");

getMethod.addRequestHeader("Content-Type", "text/html; charset=UTF-8");

这里我只是给予大家参考,实际上etContentCharset()就可以了,如果那个页面通过上述方法不能成功读取,也请指明。
如果大家有更好的方法 也请告知。





长春生活网
5
0
分享到:
评论
6 楼 w_mojian180 2014-10-17  
getParams().setContentCharset("UTF-8"); 依然乱码 不知和解
5 楼 bluestome 2011-06-14  
测试中文发布内容,不好意思拿你的帖子做实验!
4 楼 sysmaid 2009-12-30  
用getMethod.addRequestHeader("Content-Type", "text/html; charset=UTF-8");   没起作用
用post.getParams().setContentCharset("UTF-8");才可以
搞不懂这api是怎么设计的
3 楼 bdceo 2009-11-11  
最近在做一个获取Google的翻译,用的也是Httpclient,乱码也是很大的问题,头疼了好几天...也懒得去看HttpClient的源码...哎,就在google上一个一个得搜索解决方案,没想到今天在这儿解决了。
首先很感谢博主的解决方案,
然后呢,也在这儿晒晒我的google翻译...哈哈,献丑了。
发现博主提示的
post.getParams().setContentCharset("UTF-8");

这行代码,彻底解决了乱码问题。  
private static final String URL = "http://ajax.googleapis.com/ajax/services/language/translate";
/**
	 * 获取Google翻译
	 * 
	 * @param 待翻译内容
	 * @param true:中翻英,false:英翻中
	 * @return 返回翻译后的内容
	 */
	private synchronized static String doTranslate(String text, boolean flag) {
		String result = "";
		HttpClient client = null;
		PostMethod post = null;
		try {
			client = new HttpClient();
			post = new PostMethod(URL);
			NameValuePair[] params = {
					new NameValuePair("v", "1.0"),
					new NameValuePair("q", text),
					new NameValuePair("langpair", flag ? "zh-CN|en"
							: "en|zh-CN") };
			post.setRequestBody(params);
			[color=red]post.getParams().setContentCharset("UTF-8");[/color]			int status = client.executeMethod(post);
			if (status == HttpStatus.SC_OK) {
				result = post.getResponseBodyAsString();
			} else {				logger.error(">>>>>>>>> 请求翻译 :\"" + text
						+ "\" 时失败,\nHttp返回的状态码是:" + status + ",时间:"
						+ sdf.format(new Date()) + "<<<<<<<<<<");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("请求Google翻译时出错:" + GoogleTranslate.class.getName()
					+ ":" + e.getMessage());
		} finally {
			if (post != null) {
				post.releaseConnection();
				post = null;
				client = null;
			}
		}
		return parseJSON(result);
	}
private synchronized static String parseJSON(String src) {
		String result = "";
		try {
			JSONObject json = new JSONObject(src);
			JSONObject obj = json.getJSONObject("responseData");
			if (obj != null) {
				result = obj.getString("translatedText");
				result = result.replaceAll("% 26", "&");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("解析Google返回的JSON数据时出错:"
					+ GoogleTranslate.class.getName() + ":" + e.getMessage());
		}
		return result;
	}
2 楼 llying 2009-02-19  
gml520 写道

我最近也在 也在用HttpClient ,也遇到了中文乱码问题,比如:url="http://www.blcu.edu.cn/financial/musicclub/02-sunyanzi/CD3/05%20-%20星期一天气晴我离开你.mp3"调用: GetMethod getMethod = new GetMethod(url);报url异常:java.lang.IllegalArgumentException: Invalid uri 'http://www.blcu.edu.cn/financial/musicclub/02-sunyanzi/CD3/05%20-%20星期一天气晴我离开你.mp3': escaped absolute path not validat org.apache.commons.httpclient.HttpMethodBase.&lt;init&gt;(HttpMethodBase.java:219)at org.apache.commons.httpclient.methods.GetMethod.&lt;init&gt;(GetMethod.java:88)

GetMethod getMethod = new GetMethod("http://www.blcu.edu.cn/financial/musicclub/02-sunyanzi/CD3/"+URLEncoder.encode("05%20-%20星期一天气晴我离开你.mp3","UTF-8"));
1 楼 gml520 2009-02-18  
我最近也在 也在用HttpClient ,也遇到了中文乱码问题,

比如:
url="http://www.blcu.edu.cn/financial/musicclub/02-sunyanzi/CD3/05%20-%20星期一天气晴我离开你.mp3"

调用: GetMethod getMethod = new GetMethod(url);

报url异常:
java.lang.IllegalArgumentException: Invalid uri 'http://www.blcu.edu.cn/financial/musicclub/02-sunyanzi/CD3/05%20-%20星期一天气晴我离开你.mp3': escaped absolute path not valid

at org.apache.commons.httpclient.HttpMethodBase.<init>(HttpMethodBase.java:219)
at org.apache.commons.httpclient.methods.GetMethod.<init>(GetMethod.java:88)

相关推荐

Global site tag (gtag.js) - Google Analytics