HttpCLient请求困扰了两天的问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AiNiBuLiBuQi/article/details/78863317
**问题起因是测试过程中部署到阿里云服务器,通过vpn访问内网前置机发送查询报文,出现了消息无返回结果的情况**
  1. 写个小程序放在阿里云服务器充当客户端,服务端测试程序放在内网服务器上,双方分别打印日志观察消息传递情况
  2. 客户端小程序照搬了项目中发送httpclient请求的代码
  3. 服务端最初用socket模拟了接收http请求并返回信息
  4. 自己的小程序发送,响应并未出现类似状况
  5. 将客户端改成访问前置机,返回结果的频率并无任何规律,有时候有结果有时候是空字符串
  6. 修改了客户端程序,在服务端直接用controller接收http请求,然后返回结果,当然,在此期间遇见了数不清的梗儿,比如Controller要不被安全框架拦截,并且为了让项目中返回xml折腾了很久,终于发现直接请求到controller返回字符串也好,xml也好都没结果,百思不得其解了
  7. 突然发现某博客httpclient请求与我们的代码稍有差池(便是这一行:byte[] bytes = new byte[1024];)
  8. 改成这样,效果杠杠滴

客户端代码

package com.test.vpn;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

public class TestClient {
    public static final Logger logger = Logger.getLogger(TestClient.class);
    public static String connectionExceptionString = "<?xml version=\"1.0\" encoding=\"GBK\"?><stream><status>TIMEOUT</status><statusText>服务器访问出错</statusText><list name=\"userDataList\"><row><status>AAAAAAA</status><statusText>交易成功</statusText><stt>0</stt></row></list></stream>";
    static {   
        DOMConfigurator.configure(System.getProperty("user.dir") + File.separator + "conf" + File.separator   
                + "log4j.xml");   
    }
    public static String post(String url, String xmlInfo, String charset) {
        // 关闭
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
        System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient","stdout");

        // 创建httpclient工具对象
        HttpClient client = new HttpClient();
        // 创建post请求方法
        PostMethod myPost = new PostMethod(url);
        // 设置请求超时时间
        client.getHttpConnectionManager().getParams().setConnectionTimeout(300 * 1000);
        String responseString = null;
        try {
            // 设置请求头部类型
            myPost.setRequestHeader("Content-Type", "text/xml");
            myPost.setRequestHeader("charset", charset);

            // 设置请求体,即xml文本内容,注:这里写了两种方式,一种是直接获取xml内容字符串,一种是读取xml文件以流的形式
            myPost.setRequestEntity(new StringRequestEntity(xmlInfo, "text/xml", charset));
            //myPost.setRequestEntity(new StringRequestEntity(xmlString,"text/xml","utf-8"));
            int statusCode = client.executeMethod(myPost);
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(statusCode);
            if (statusCode == HttpStatus.SC_OK) {
                BufferedInputStream bis = new BufferedInputStream(myPost.getResponseBodyAsStream());
                byte[] bytes = new byte[1024];
//              byte[] bytes = new byte[bis.available()];
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                int count = 0;
                while ((count = bis.read(bytes)) != -1) {
                    if(count == 0){
                        break ;
                    }
                    bos.write(bytes, 0, count);
                }
                byte[] strByte = bos.toByteArray();
                responseString = new String(strByte, 0, strByte.length, charset);
                logger.info("返回结果:"+responseString);
                bos.close();
                bis.close();
            }
        }catch (Exception e) {
            logger.info("",e);
            return connectionExceptionString;
        }finally{
            if(myPost != null) myPost.releaseConnection();
        }

        return responseString;
    }
    public static void main(String[] args) {
        for(int i=0; i<100; i++){
            logger.info("第"+i+"次");
            StringBuffer sb = new StringBuffer();
            sb.append("<?xml version=\"1.0\" encoding=\"GBK\"?>");
            sb.append("<stream><action>DLSBALQR</action><userName>XXX</userName><accountNo>11</accountNo><subAccNo>010</subAccNo></stream>");

            logger.info("发送内容"+sb.toString());
            TestClient.post("http://192.168.0.100:8080/v2/appTestVpn/testVpn.app", sb.toString(), "GBK");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
展开阅读全文

没有更多推荐了,返回首页