`

HTTPClient PostMethod 乱码问题

阅读更多

虽然这是篇老文,不过还是忍不住转过来看看。

 

类别标签: UTF-8 encoding http-client java 
HttpClient POST 的 UTF-8 编码问题 
Apache HttpClient ( http://jakarta.apache.org/commons/httpclient/ ) 是一个纯 Java 的HTTP 协议的客户端编程工具包, 对 HTTP 协议的支持相当全面, 更多细节也可以参考IBM 网站上的这篇文章 HttpClient入门 ( http://www-128.ibm.com/developerworks/cn/opensource/os-httpclient/ ). 

问题分析 
不过在实际使用中, 还是发现按照最基本的方式调用 HttpClient 时, 并不支持 UTF-8 编码, 在网络上找过一些文章, 也不得要领, 于是查看了 commons-httpclient-3.0.1 的一些代码, 首先在 PostMethod 中找到了 generateRequestEntity() 方法: 

/** 
* Generates a request entity from the post parameters, if present. Calls 
* {@link EntityEnclosingMethod#generateRequestBody()} if parameters have not been set. 
* 
* @since 3.0 
*/ 
protected RequestEntity generateRequestEntity() { 
if (!this.params.isEmpty()) { 
// Use a ByteArrayRequestEntity instead of a StringRequestEntity. 
// This is to avoid potential encoding issues. Form url encoded strings 
// are ASCII by definition but the content type may not be. Treating the content 
// as bytes allows us to keep the current charset without worrying about how 
// this charset will effect the encoding of the form url encoded string. 
String content = EncodingUtil.formUrlEncode(getParameters(), getRequestCharSet()); 
ByteArrayRequestEntity entity = new ByteArrayRequestEntity( 
EncodingUtil.getAsciiBytes(content), 
FORM_URL_ENCODED_CONTENT_TYPE 
); 
return entity; 
} else { 
return super.generateRequestEntity(); 
} 
} 

 

原来使用 NameValuePair 加入的 HTTP 请求的参数最终都会转化为 RequestEntity 提交到 HTTP 服务器, 接着在 PostMethod 的父类 EntityEnclosingMethod 中找到了如下的代码: 

/** 
* Returns the request's charset. The charset is parsed from the request entity's 
* content type, unless the content type header has been set manually. 
* 
* @see RequestEntity#getContentType() 
* 
* @since 3.0 
*/ 
public String getRequestCharSet() { 
if (getRequestHeader("Content-Type") == null) { 
// check the content type from request entity 
// We can't call getRequestEntity() since it will probably call 
// this method. 
if (this.requestEntity != null) { 
return getContentCharSet( 
new Header("Content-Type", requestEntity.getContentType())); 
} else { 
return super.getRequestCharSet(); 
} 
} else { 
return super.getRequestCharSet(); 
} 
} 

 

解决方案 
从上面两段代码可以看出是 HttpClient 是如何依据 "Content-Type" 获得请求的编码(字符集), 而这个编码又是如何应用到提交内容的编码过程中去的. 按照这个原来, 其实我们只需要重载 getRequestCharSet() 方法, 返回我们需要的编码(字符集)名称, 就可以解决 UTF-8 或者其它非默认编码提交 POST 请求时的乱码问题了. 


测试 
首先在 Tomcat 的 ROOT WebApp 下部署一个页面 test.jsp, 作为测试页面, 主要代码片段如下: 

<%@ page contentType="text/html;charset=UTF-8"%> 
<%@ page session="false" %> 
<% 
request.setCharacterEncoding("UTF-8"); 
String val = request.getParameter("TEXT"); 
System.out.println(">>>> The result is " + val); 
%> 

 
接着写一个测试类, 主要代码如下: 

public static void main(String[] args) throws Exception, IOException { 
String url = "http://localhost:8080/test.jsp"; 
PostMethod postMethod = new UTF8PostMethod(url); 
//填入各个表单域的值 
NameValuePair[] data = { 
new NameValuePair("TEXT", "中文"), 
}; 
//将表单的值放入postMethod中 
postMethod.setRequestBody(data); 
//执行postMethod 
HttpClient httpClient = new HttpClient(); 
httpClient.executeMethod(postMethod); 
} 

//Inner class for UTF-8 support 
public static class UTF8PostMethod extends PostMethod{ 
public UTF8PostMethod(String url){ 
super(url); 
} 
@Override 
public String getRequestCharSet() { 
//return super.getRequestCharSet(); 
return "UTF-8"; 
} 
} 

 
运行这个测试程序, 在 Tomcat 的后台输出中可以正确打印出 ">>>> The result is 中文" . 

代码下载 
本文所提到的所有代码, 以及测试程序(可直接导入 eclipse)提供打包下载: att:HttpClient POST 的 UTF-8 编码问题.httpClientUTF8.tar.bz2 

 

 

 

原文:http://zhangxinzhou.blog.ccidnet.com/blog-htm-do-showone-type-blog-itemid-350984-uid-36421.html

1
0
分享到:
评论

相关推荐

    HttpClient PostMethod 上传文件

    在本示例中,我们将深入探讨如何使用HttpClient的PostMethod来上传文件,以及处理Get和Post请求中的乱码问题。 一、HttpClient基础 HttpClient库提供了一套完整的API,允许我们构建复杂的HTTP请求。它支持GET、POST...

    彻底解决httpClient乱码问题

    本文将深入探讨如何使用HttpClient来彻底解决乱码问题。 HttpClient是一个功能强大的HTTP客户端,支持多种HTTP协议版本,包括GET、POST等请求方法,以及重试、连接管理等功能。在处理中文字符时,由于编码不一致...

    HttpClient、乱码解决:实例

    本篇将详细介绍如何使用HttpClient解决乱码问题。 一、HttpClient基本使用 HttpClient主要由以下几个核心组件构成: 1. HttpClient:客户端实例,负责管理连接、配置请求等。 2. HttpRequestBase:表示HTTP请求,如...

    解决HttpClient中文乱码问题jar文件

    HttpClient中文乱码问题的核心在于字符编码不一致或者未明确指定。默认情况下,HttpClient可能使用ISO-8859-1作为编码,而我们的中文字符通常需要UTF-8编码才能正确显示。以下是一些解决HttpClient中文乱码问题的...

    httpclient4上传文件中文乱码问题解决办法代码示例

    服务器端自己写,本示例为客户端代码,可以解决httpClient4乱码问题,是替代修改源码的最佳写法。

    HttpClient4.2.5上传文件,无中文文件名乱码问题

    HttpClient4.2.5实现文件上传,无中文文件名乱码问题。亲测无问题。有问题可吐槽!

    Httpclient使用jar包三合一,基本使用方法

    PostMethod method = new PostMethod(str1); try { // 需要添加的header数据 List&lt;Header&gt; headers = new ArrayList(); headers.add(new Header("", "")); headers.add(new Header("", "")); ...

    使用httpclient解决跨域问题

    我使用的是httpClient 进行内部转发 我们在A的服务器上,将前台的文件流,通过httpClient传输到B的服务器上(B的服务器通过控制层接受A传输的文件流,让后保存在B的服务器上。返回一个json结果)

    可用org.apache.commons.httpclient-3.1.0.jar.zip

    import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;...

    HttpClient

    import org.apache.commons.httpclient.methods.PostMethod; public class HttpClientExample { public static void main(String[] args) throws Exception { HttpClient httpClient = new HttpClient(); ...

    commons-httpclient-3.1短信发送包

    4. 参数编码:在设置请求参数时,确保正确地对字符串进行URL编码,防止乱码问题。 总结,Apache Commons HttpClient 3.1是一个功能强大的HTTP客户端库,虽然在现代开发中可能有更先进的选择,但它仍能满足基本的...

    httpclient.jar包下载

    4. **重试和恢复策略**:HttpClient内置了重试和恢复策略,当网络出现问题时,可以自动进行重试,保证请求的可靠性。 5. **异步和同步模式**:HttpClient提供同步和异步两种操作模式,适应不同场景的需求。 提到...

    httpclient 上传文件

    在本篇文章中,我们将深入探讨如何使用HTTPClient上传文件以及解决可能出现的乱码问题。 首先,让我们关注“httpclient 上传文件”。在HTTP协议中,文件上传通常涉及到POST请求,特别是当Content-Type设置为...

    commons-httpclient-3.0.jar JAVA中使用HttpClient可以用到

    2. **HttpMethod**:HttpClient提供了多种HttpMethod子类,如GetMethod、PostMethod等,分别对应HTTP的GET、POST等请求方法。 3. **Request和Response**:HttpClient通过发送HttpRequest对象并接收HttpResponse对象...

    httpclient测试请求方法

    2. **commons-codec**:提供了各种编码算法,如Base64、URL编码和ASCII85编码,HttpClient用它来处理请求和响应中的编码问题,特别是在处理URL、表单数据和HTTP头时。 在使用HttpClient时,我们首先需要导入相关...

    httpClient调用webservice接口

    HttpClient不仅支持HTTP协议,还支持HTTPS等其他协议,并且能够处理重定向、代理服务器以及身份验证等问题。此外,HttpClient还具有很高的灵活性和可扩展性,能够满足各种复杂的网络请求需求。 #### 三、调用...

    httpclientjar包

    在实际使用中,HttpClient可能会遇到各种问题,如DNS解析错误、连接超时、证书验证失败等。这些问题通常需要根据具体的错误信息进行调试和解决,可能涉及到调整HttpClient的配置参数,或者处理特定的异常。 总的来...

    httpclient-4.5jar

    httpclient-4.5所需jar包,里面包含httpclient-4.5.jar等等10个必须的开发包。 1.commons-codec-1.9.jar 2.commons-logging-1.2.jar 3.fluent-hc-4.5.jar 4.httpclient-4.5.jar 5.httpclient-cache-4.5.jar 6....

    commons-httpclient-3.1.jar

    import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.ByteArrayRequestEntity; import org.apache.commons.httpclient.methods.PostMethod;

    HttpClient介绍和使用文档

    在处理文件上传的问题上,HttpClient也提供了便捷的方法,使得开发者可以轻松地发送POST请求并附带文件数据。 以下是一个使用HttpClient简单读取网页内容的例子: ```java import java.io.IOException; import org...

Global site tag (gtag.js) - Google Analytics