特别坑,给一个公司的内网部署一台服务器,现象是自己本地没有问题,部署到他们的服务器上就有问题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就可以成功得到对方接口的返回值了,成功失败都好,给个信最美了