package com.example.demo.test;
import com.example.demo.test.config.MyX509TrustManager;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
public class demo1 {
public static void main(String[] args) throws IOException {
String str="江苏省gdp";
String urlString="https://data.stats.gov.cn/search.htm?s="+str+"&m=searchdata&db=&p=0";
BufferedReader in=null;
StringBuffer result = new StringBuffer();
try {
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
// 打开和URL之间的连接
URL realUrl= new URL(null, urlString, new sun.net.www.protocol.https.Handler());
HttpsURLConnection connection = (HttpsURLConnection) realUrl.openConnection();
connection.setSSLSocketFactory(ssf);
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("content-Type", "application/json");
connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestMethod("GET");
//Get请求不需要DoOutPut
connection.setDoOutput(false);
connection.setDoInput(true);
//连接服务器
connection.connect();
// 取得输入流,并使用Reader读取
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
System.out.println(result);
} catch (IOException | NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}