博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
远程部署项目,修改catalina.bat文件 完美解决在代理服务器上HttpURLConnection 调接口超时的问题...
阅读量:6271 次
发布时间:2019-06-22

本文共 5282 字,大约阅读时间需要 17 分钟。

远程给客户部署项目,运行时程序调外部接口时总是出不去,经过不懈努力,后来发现客户那边的网络走的是代理,于是在代码中加下面代码:

//设置代理  System.setProperty("http.proxySet", "true");  System.setProperty("http.proxyHost", "代理ip地址");  System.setProperty("http.proxyPort", "8080");

调试后,汗~~~不管用,又开始找资料,请教别人后才知道 只要在Tomcat的..\bin\catalina.bat文件里添加代理就可以了

找到set JAVA_OPTS加上如下代码即可:

set JAVA_OPTS=%JAVA_OPTS% -server -XX:PermSize=128M -XX:MaxPermSize=512m -Dhttp.proxyHost=代理服务器ip -Dhttp.proxyPort=代理服务器端口 -Dhttps.proxyHost=代理服务器ip -Dhttps.proxyPort=代理服务器端口

 心想这下应该可以正常运行了吧,结果还是超时,最后干脆用java的原始类HttpURLConnection替换掉第三方开源框架类HttpClient,运行后,OK ! ! ! ~

以下是部分代码:

package com.bwdz.fp.saas.util;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.net.URL;import java.net.URLEncoder;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import java.util.Map;import javax.net.ssl.HttpsURLConnection;import javax.net.ssl.SSLContext;import javax.net.ssl.TrustManager;import javax.net.ssl.X509TrustManager;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;public class HttpsFptClient {    private static Logger logger = Logger.getLogger(CYInterface.class);    private static TrustManager myX509TrustManager = new X509TrustManager() {        public void checkClientTrusted(X509Certificate[] arg0, String arg1)                throws CertificateException {        }        public void checkServerTrusted(X509Certificate[] arg0, String arg1)                throws CertificateException {        }        public X509Certificate[] getAcceptedIssuers() {            return null;        }    };    public static String doPost(String url,Map
map,String charset){ HttpClient httpClient = null; HttpPost httpPost = null; String result = null; try{ /*httpClient = new SSLClient(); httpClient.getParams().setIntParameter("http.socket.timeout",120000); httpPost = new HttpPost(url); //设置参数 List
list = new ArrayList
(); Iterator iterator = map.entrySet().iterator(); while(iterator.hasNext()){ Entry
elem = (Entry
) iterator.next(); list.add(new BasicNameValuePair(elem.getKey(),elem.getValue())); } if(list.size() > 0){ UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset); httpPost.setEntity(entity); } HttpResponse response = httpClient.execute(httpPost); if(response != null){ HttpEntity resEntity = response.getEntity(); if(resEntity != null){ result = EntityUtils.toString(resEntity,charset); } } */ SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[]{myX509TrustManager}, null); URL console = new URL(url); HttpsURLConnection conn = (HttpsURLConnection) console.openConnection(); int timeout = 30000; conn.setConnectTimeout(timeout); conn.setReadTimeout(timeout); conn.setSSLSocketFactory(sslcontext.getSocketFactory()); //conn.setHostnameVerifier(new TrustAnyHostnameVerifier()); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.connect(); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); String requestData = parseParams(map); out.write(requestData.getBytes(charset)); // 刷新、关闭 out.flush(); out.close(); String responeStr = readStream(conn.getInputStream()); return responeStr; } catch (Exception e) { logger.error("https post error: " + e.getMessage()+",url:"+url); return null; } } /** * 将map转为字符串 * * @param params * @return * @throws UnsupportedEncodingException */ private static String parseParams(Map
params) throws UnsupportedEncodingException { StringBuilder stringBuilder = new StringBuilder(); for (Map.Entry
entry : params.entrySet()) { stringBuilder.append(URLEncoder.encode(entry.getKey(), "utf-8")); stringBuilder.append("="); stringBuilder.append(URLEncoder.encode(entry.getValue() == null ? "" : entry.getValue(), "utf-8")); stringBuilder.append("&"); } String str = stringBuilder.toString(); if (str.length() > 0) { str = str.substring(0, str.length() - 1); } return str; } /** * 读取流 * * @param inputStream * @return * @throws IOException */ private static String readStream(InputStream inputStream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8")); String line = null; StringBuffer sb = new StringBuffer(); while ((line = reader.readLine()) != null) { sb.append(line); } reader.close(); return sb.toString(); }}

 

转载于:https://www.cnblogs.com/maxmoore/p/8242805.html

你可能感兴趣的文章
asp.net core 2.0 web api基于JWT自定义策略授权
查看>>
Skype for Business Server 2015-04-前端服务器-3-安装-管理工具
查看>>
第12章代码《跟老男孩学习Linux运维:Shell编程实战》
查看>>
我们为什么从Python转到go?
查看>>
5.Azure负载均衡(上)
查看>>
轻松精通awk数组企业问题案例
查看>>
26.Azure备份服务器(下)
查看>>
从“网上说的能信么”说开去---学习的思考
查看>>
DHCP 日志分析
查看>>
.NET Micro Framework动态调用C/C++底层代码(原理篇)
查看>>
Windows Server 2012正式版RDS系列⒃
查看>>
Shell脚本之awk篇
查看>>
微软发布Azure Stack硬件需求
查看>>
python socket编程详细介绍
查看>>
Windows Server 2016第三个技术预览版新技术
查看>>
Everything 本地磁盘文件搜索工具下载!
查看>>
Python dict(字典) 详细总结
查看>>
RPF(Reverse Path Forwarding 反向路径转发)技术
查看>>
2016年收到的第一件礼物,被评上微软全球最有价值专家MVP(一)
查看>>
2016中国VR开发者论坛第一期
查看>>