前言:工作中遇到两个系统之间通信的问题,需求是这样的:要求将信息上报给上级部门(这里的上级部门是两一个系统),这就是跨系统通信了
解决方案:使用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方法发送请求:
//创建PostMethod的子类设置编码格式
public static class UTF8PostMethod extends PostMethod{
public UTF8PostMethod(String url){
super(url);
}
@Override
public String getRequestCharSet() {
//return super.getRequestCharSet();
return "UTF-8";
}
}
JSONObject json = JSONObject.fromObject(event);//将java对象转换为json对象
String str = json.toString();//将json对象转换为字符串
String url = "http://172.20.57.87:8080/gyly_ec_new3/api/mobileservices/district";//接口url
HttpClient client = new HttpClient();//创建httpClient对象
PostMethod post = new UTF8PostMethod(url);//创建PostMethod的子类UTF8PostMethod来设置编码
NameValuePair message = new NameValuePair("json", str);//post请求必须使用 NameValuePair 类传递参数
post.setRequestBody(new NameValuePair[]{message});
try {
int code=client.executeMethod(post);//发送数据
if (code==200) {
System.out.println("请求成功!");
}else {
System.out.println("请求失败!");
}
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
post.releaseConnection();//关闭连接
}
上面的代码都有备注。
主要说一下:
PostMethod post = new UTF8PostMethod(url);//创建PostMethod的子类UTF8PostMethod来设置编码
这里使用postMethod 对象,防止中文乱码,必须创建其子类
UTF8PostMethod
设置编码,才可以防止中文乱码。
结语:在网上看了很多种httpclient的用法,自己在做的时候也遇到很多问题,现在问题解决了,写博客的时候却感觉没什么可写的,关键是找到正确的方式。如上代码中我已经实现,并且可以使用。
如果你恰好也有同样的需求,在看了我的代码后有不明白的地方,可以给我留言,或者加我的qq:416404891,我会尽力给你解答。
互相学习。。。。。。。。。。。。。。。。。。
晚安!