Mark一下 httppost 本地可用, 自己的服务器可用,部署到安全性比较高的某公司内部服务器就timeout了

16 篇文章 0 订阅
10 篇文章 0 订阅

特别坑,给一个公司的内网部署一台服务器,现象是自己本地没有问题,部署到他们的服务器上就有问题curl一个外网接口可以curl通,但是用我的java服务包了一层就不可用,神奇,post请求发出去石沉大海,然后timeout 掉。然后部署到我们服务器上发现没有问题那肯定不是代码的问题,是他们服务器限制什么了。问他们公司的说没有限制。然后试了很多种方式,最后有效果的是用Python包了一层就可以访问,后来看着两个代码有什么区别发现python真是太轻量了,java httppost要一堆代码Python就一行解决,猜想应该是python的requests.post()方法是支持代理的。我在本地测试和我们服务器上根本没写代理相关的代码。果然上他们服务器上的profile中搜到代理相关的信息。我改造了下我的代码如下:

public String requestProxyForHttp(String url, Map<String, String> requestParams) throws Exception {
        
        HttpHost proxy = new HttpHost("proxyUrl", "ProxyPort", "http");//设置代理IP、端口、协议 替换成自己的

        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setProxy(proxy)
                .build();//把代理设置到请求配置

        String result = null;
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
        /** HttpPost */
        HttpPost httpPost = new HttpPost(url);

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        Iterator<Map.Entry<String, String>> it = requestParams.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> en = it.next();
            String key = en.getKey();
            String value = en.getValue();
            if (value != null) {
                params.add(new BasicNameValuePair(key, value));
            }
        }
        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
   
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        try {
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity, "utf-8");
            EntityUtils.consume(httpEntity);
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
            } catch (IOException e) {
                log.info("http send post request error" + e);
            }
        }
        return result;
    }

注意这个HttpHost的第三个参数,按道理是应该根据url是不是https的设定是http还是https的,我们这个接口应该是https但是配成http却不好用报错:proxy unrecognized SSL message,plaintext connection,改成http就可以成功得到对方接口的返回值了,成功失败都好,给个信最美了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值