[size=medium]最近项目用到httpclient.代理游戏充值功能,在本系统充值完毕后,划拨到对方游戏。需要对方提供http服务,本系统充值成功调用。
传递参数和接收内容中涉及到中文,个人解决方法如下:[/size]
[size=medium]参数传递:[/size]
[size=medium]Get接收参数需要在tomcat的server.xml修改[/size]
[size=medium]POST处理编码需要在servlet中添加[/size]
传递参数和接收内容中涉及到中文,个人解决方法如下:[/size]
[size=medium]参数传递:[/size]
//创建请求参数
private HttpUriRequest createRequest(String method, String urlStr, Map<String, String> params){
try {
if (method.equalsIgnoreCase("get")) {
URI uri = makeURI(urlStr, params);
HttpGet httpGet = new HttpGet(uri);
return httpGet;
} else {
HttpPost httpPost = new HttpPost(urlStr);
List<NameValuePair> nvps=new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));
return httpPost;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private URI makeURI(String urlStr, Map<String, String> params) {
URIBuilder uriBuilder = null;
URI uri = null;
try {
uriBuilder = new URIBuilder(urlStr);
for (Map.Entry<String, String> entry : params.entrySet()) {
uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
//URIBuilder内部用utf-8编码
uri = uriBuilder.build();
} catch (URISyntaxException e) {
e.printStackTrace();
}
try {
log.debug("The uri = " + uri.toURL());
} catch (MalformedURLException e) {
e.printStackTrace();
}
return uri;
}
[size=medium]Get接收参数需要在tomcat的server.xml修改[/size]
<Connector port="8080" maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" URIEncoding='UTF-8' />
[size=medium]POST处理编码需要在servlet中添加[/size]
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");