/** * Generates a request entity from the post parameters, if present. Calls *{@link EntityEnclosingMethod#generateRequestBody()}if parameters have not been set. * *@since3.0 */ protectedRequestEntity 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 =newByteArrayRequestEntity( EncodingUtil.getAsciiBytes(content), FORM_URL_ENCODED_CONTENT_TYPE ); returnentity; }else{ return super.generateRequestEntity(); } }
/** * 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. * *@seeRequestEntity#getContentType() * *@since3.0 */ publicString 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) { returngetContentCharSet( newHeader("Content-Type", requestEntity.getContentType())); }else{ return super.getRequestCharSet(); } }else{ return super.getRequestCharSet(); } }
<%@ 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 staticvoidmain(String[]args)throwsException, IOException{ String url ="http://localhost:8080/test.jsp"; PostMethod postMethod =newUTF8PostMethod(url); //填入各个表单域的值 NameValuePair[]data =http://www.mamicode.com/{ newNameValuePair("TEXT","中文"), }; //将表单的值放入postMethod中 postMethod.setRequestBody(data); //执行postMethod HttpClient httpClient=newHttpClient(); httpClient.executeMethod(postMethod); } //Inner class for UTF-8 support public static classUTF8PostMethodextendsPostMethod{ publicUTF8PostMethod(String url){ super(url); } @Override publicString getRequestCharSet() { //return super.getRequestCharSet(); return"UTF-8"; } }
运行这个测试程序, 在 Tomcat 的后台输出中可以正确打印出 ">>>> The result is 中文" .