1、HTTP共用方法
public String doHttp(String urlStr, String output){
StringBuilder sb = new StringBuilder();
HttpsURLConnection connection = null;//http链接
try {
//创建SSLContext
SSLContext sslContext=SSLContext.getInstance("TLS");
System.setProperty("https.protocols", "TLSv1");
TrustManager[] tm={new MyX509TrustManager()};
//初始化
sslContext.init(null, tm, new java.security.SecureRandom());;
//获取SSLSocketFactory对象
SSLSocketFactory ssf=sslContext.getSocketFactory();
URL url = new URL(urlStr);//url创建
connection = (HttpsURLConnection) url.openConnection();//打开链接
connection.setRequestMethod("POST");//设置请求方法。还可以设置其他参数
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setConnectTimeout(5000);
connection.setReadTimeout(30000);
connection.setUseCaches(false);
connection.setSSLSocketFactory(ssf);
connection.setRequestProperty("Content-Type", "application/json");
if (output != null) {
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), Charset.forName("UTF-8"));
out.write(output);
out.flush();
out.close();
}
connection.connect();//正式链接请求
InputStream in = connection.getInputStream();//正确返回结果,获得输入流
//读取内容
InputStreamReader isr = new InputStreamReader(in, "UTF-8");
BufferedReader br = new BufferedReader(isr);//按行读取
String temp = null;
while ((temp = br.readLine()) != null) {//读取内容
sb.append(temp);
}
br.close();
isr.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("未能正常连接到消息方服务!", e);
} finally {
//关闭链接
if (connection != null) {
connection.disconnect();
}
}
return sb.toString();
}
2、调用
//json 入参
//url 字符串地址
//str 为返回值
String str = doHttp(url, json.toString());