解决方案:使用httpclient实现网络通信,传递数据。
关键问题:httpClient postMethod 传递参数 防止中文乱码
一,所需jar包
maven引用如下:
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging-api</artifactId>
<version>1.1</version>
</dependency>
二,使用httpclient的postMethod方法发送请求:
public static String getConnectPushData(String xml,String method,String param1) throws Exception {
//方法2:利用HttpClient post调用接口
String result="";
HttpClient httpClient = new HttpClient();
// 服务器地址
String urlString="http://222.90.31.87:8888/JCSJJC/WebService/IntegrationService.asmx";
PostMethod post = new UTF8PostMethod(urlString+"/PushData");//这里使用postMethod 对象,防止中文乱码,必须创建其子类UTF8PostMethod设置编码,才可以防止中文乱码。
post.setParameter("data", xml);
post.setParameter("bussiness", param1);
int status = httpClient.executeMethod(post);
if (200 != status) {
result="{\"Code\":\"-3\",\"Message\":\"失败,\",\"Data\":{}}";
}else{
result = new String(post.getResponseBody(), "UTF-8");
}
return result;
}
//创建PostMethod的子类设置编码格式
public static class UTF8PostMethod extends PostMethod{
public UTF8PostMethod(String url){
super(url);
}
@Override
public String getRequestCharSet() {
return "UTF-8";
}
}
主要说一下:
PostMethod post = new UTF8PostMethod(url);//创建PostMethod的子类UTF8PostMethod来设置编码
这里使用postMethod 对象,防止中文乱码,必须创建其子类
UTF8PostMethod
设置编码,才可以防止中文乱码。