最近比较忙,谢了个小程序,通过post方法传值。
在红色字体的那段代码是通过 Post 传汉字的,要先获取原先的汉字编码方式,再去转码,应为和服务器之间的传码使用的是 ISO-8859-1 ,所以要将汉字转码为 ISO-8859-1 才可以正常传值。
public static String getdata() throws UnsupportedEncodingException {
String search="android";
HttpClient client = new HttpClient();
client.getHostConfiguration().setHost("HOST的网址", 端口号);
PostMethod post = new PostMethod("Post的目标网址");
NameValuePair B1 = new NameValuePair("B1", "检 索");
NameValuePair hidWxlx = new NameValuePair("hidWxlx", "spanCNLx");
NameValuePair nMaxCount = new NameValuePair("nMaxCount", "100");
NameValuePair nSetPageSize = new NameValuePair("nSetPageSize", "10");
NameValuePair txtLx = new NameValuePair("txtLx", "%");
NameValuePair txtPY = new NameValuePair("txtPY", "HZ");
NameValuePair txtSearchType = new NameValuePair("txtSearchType", "1");
NameValuePair txtTm = new NameValuePair("txtTm",new String(search.getBytes("gbk"),"ISO-8859-1"));
NameValuePair txtWxlx = new NameValuePair("txtWxlx", "CN");
post.setRequestBody(new NameValuePair[] { B1, hidWxlx, nMaxCount,
nSetPageSize, txtLx, txtPY, txtSearchType, txtTm, txtWxlx });
try {
client.executeMethod(post);
} catch (HttpException e2) {
} catch (IOException e2) {
}
// 将POST返回的数据以流的形式读入,再把输入流流至一个buff缓冲字节数组
byte[] buff = null;
try {
buff = StreamTool
.readInputStream(post.getResponseBodyAsStream());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 将返回的内容格式化为String存在html中
String html = new String(buff);
System.out.println(html);
// 任务完成了,释放连接
post.releaseConnection();
}