欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

httpclient 中文乱码的解决方案

程序员文章站 2022-05-30 23:26:46
...

最近写个httpclient post的方法如下

 

public static void sendData(String url, String value[], String key[])
			throws IOException {
		HttpClient client = new HttpClient();
		// 设置代理服务器地址和端口
		 client.getHostConfiguration().setProxy("172.17.18.80",8080);
		// client.getHostConfiguration().setHost(host, port, "http");
		PostMethod postMethod = new PostMethod(url);
		NameValuePair p1 = new NameValuePair(key[0], value[0]);
		NameValuePair p2 = new NameValuePair(key[1], value[1]);

		postMethod.setRequestBody(new NameValuePair[] { p1, p2 });
		postMethod.setRequestHeader("Content-Type", "text/html;charset=gb2312");
		// 使用POST方式提交数据
		client.executeMethod(postMethod);
		// 打印服务器返回的状态
		logger.info("服务器返回的状态=" + postMethod.getStatusLine());
		// 打印结果页面
		String response = new String(postMethod.getResponseBodyAsString()
				.getBytes("gb2312"));
		// 打印返回的信息
		logger.info("返回的信息=" + response);
		// 释放连接
		postMethod.releaseConnection();
	}

 

 使用 postMethod.setRequestHeader("Content-Type", "text/html;charset=gb2312");  客户端接受的值是个null

 后改成  postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "gb2312"); 问题解决 很是奇怪

 

完整代码如下

public static void sendData(String url, String value[], String key[])
			throws IOException {
		HttpClient client = new HttpClient();
		// 设置代理服务器地址和端口
		// client.getHostConfiguration().setProxy("172.17.18.80",8080);
		// client.getHostConfiguration().setHost(host, port, "http");
		PostMethod postMethod = new PostMethod(url);
		postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "gb2312");
		NameValuePair p1 = new NameValuePair(key[0], value[0]);
		NameValuePair p2 = new NameValuePair(key[1], value[1]);

		postMethod.setRequestBody(new NameValuePair[] { p1, p2 });
		// 使用POST方式提交数据
		client.executeMethod(postMethod);
		// 打印服务器返回的状态
		logger.info("服务器返回的状态=" + postMethod.getStatusLine());
		// 打印结果页面
		String response = new String(postMethod.getResponseBodyAsString()
				.getBytes("gb2312"));
		// 打印返回的信息
		logger.info("返回的信息=" + response);
		// 释放连接
		postMethod.releaseConnection();
	}

 

相关标签: HTML