使用httpclient访问网页,进行留言时出现了中文乱码,用的是post方法,麻烦大家看下程序
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.cookie.*;
import org.apache.commons.httpclient.methods.*;
public class FormLoginDemo {
static final String LOGON_SITE = "127.0.0.1 ";
static final int LOGON_PORT = 8080;
public static void main(String[] args) throws Exception{
HttpClient client = new HttpClient();
client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT);
//模拟登录页面
PostMethod post = new PostMethod( "/os/checkuser.jsp ");
NameValuePair name = new NameValuePair( "username ", "admin ");
NameValuePair pass = new NameValuePair( "password ", "admin ");
post.setRequestBody(new NameValuePair[]{name,pass});
int status = client.executeMethod(post);
System.out.println( "登录通过 ");
post.releaseConnection();
//访问所需的页面
PostMethod post1 = new PostMethod( "/os/submit.jsp ");
NameValuePair title=new NameValuePair( "title ", new String( "测试3 ".getBytes( "iso8859_1 ")));
NameValuePair title = new NameValuePair( "title ", "测试3 ");
post1.setRequestBody(new NameValuePair[]{title,content});
client.executeMethod(post1);
System.out.println(post1.getResponseBodyAsString());
post1.releaseConnection();
}
}
要接收数据的jsp网页部分源码如下:
<%@ page contentType= "text/html; charset=gb2312 " language= "java " import= "java.sql.* " errorPage= " " %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN " "http://www.w3.org/TR/html4/loose.dtd ">
<jsp:useBean id= "dbconn " scope= "page " class= "os.osconn "/>
<html>
<head>
<META http-equiv=Content-Type content= "text/html; charset=gb2312 ">
<link rel= "stylesheet " href= "b.css " type= "text/css ">
<title> 题目 </title>
</head>
<body>
<div id= "c ">
<div id= "c1 "> </div>
<div id= "c2 ">
<%
if(session.getAttribute( "roleid ")!=null&&!session.getAttribute( "roleid ").equals( " "))
{
String sTitle = new String(request.getParameter( "title ").getBytes( "iso8859_1 "));
String sContent = new String(request.getParameter( "content1 ").getBytes( "iso8859_1 "));
略………………………………
[解决办法]
对HttpClient传输编码设置下
client.getParams().setContentCharset( "GBK ");
一般中间不需要有编码转换
传参时用URIUtil中的encode和deencode方法来编码