使用httpclient的postMethod方法发送请求对方接收报文中文乱码

解决方案:使用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

设置编码,才可以防止中文乱码。

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值