找了很大一圈,终于解决了这个中文乱码问题。直接看源码:
/**
* init Openfire User via httpRequest dml@2012.9.14
*
* @param url
*/
private static void httpExecute(String url) {
// 构造HttpClient的实例
HttpClient httpClient = new HttpClient();
// 设置 Http 连接超时为5秒
httpClient.getHttpConnectionManager().getParams()
.setConnectionTimeout(5000);
// 创建post方法的实例
PostMethod postMethod = new PostMethod(url);
// 处理中文乱码 dml@2013.1.7
postMethod.getParams().setParameter(
HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
// 设置请求超时为 5 秒
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
// 使用系统提供的默认的恢复策略
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
try {
// 执行postMethod
int statusCode = httpClient.executeMethod(postMethod);
if (statusCode != HttpStatus.SC_OK) {
log.warning("Method failed: " + postMethod.getStatusLine());
}
// 读取内容 ,第一种方式获取
byte[] responseBody = postMethod.getResponseBody();
// 处理内容
log.info(new String(responseBody));
} catch (HttpException e) {
// 发生致命的异常,可能是协议不对或者返回的内容有问题
log.info("Please check your provided http address!");
e.printStackTrace();
} catch (IOException e) {
// 发生网络异常
e.printStackTrace();
} finally {
// 释放连接
postMethod.releaseConnection();
}
}
传入参数url:
String HttpRequestURL = "http://127.0.0.1:9090/userservice?type=add&username="+ username + "&password=" + encryptedPassword + "&name=" + URLEncoder.encode(name, "UTF-8");
总结:
1.url中汉字进行URLEncoder.encode(xxxx, "UTF-8")处理;(处理后url:http://127.0.0.1:9090/userservice?type=add&username=lh&password=lh&name=%E6%9D%4E%E6%8D%8E)
2.设置编码格式postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8")。
dml@2013.1.8