Java发起http请求并解析JSON返回数据
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
💬相关
http 协议
https://www.cnblogs.com/mqy1/p/13884964.html
发起 http 请求并获得返回数据
📑来源
代码源自博客《JAVA如何调用对方http接口得到返回数据》
https://cloud.tencent.com/developer/article/2081582
public String getURLContent(String urlWithNoPara, String para) throws Exception {
String strURL = urlWithNoPara + para;
URL url = new URL(strURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
// 设置请求方法
httpConn.setRequestMethod("GET");
// POST请求必须设置下面两项
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.connect();
// 读取文件并将内容转换为字符输出
InputStream inStream = httpConn.getInputStream();
int n;
while ((n = inStream.read()) != -1){
System.out.print((char)n);
}
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
httpConn.disconnect();
String res = buffer.toString();
// 输出字符串形式的返回数据
System.out.println(res);
return res;
}
添加 http 请求头
在前文 HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
和 httpConn.connect();
之间添加以下代码
httpConn.setRequestProperty(key,value); // key 和 value 是你需要添加的头信息的键与值
忽略验证 https 中 SSL 证书
一般用于 SSL 证书失效却又不得不以 https 去请求的情况如报错 java.security.cert.CertificateException: No subject alternative names matching IP address xxx.xxx.xxx.xxx found
在发起 https 请求前调用下文 disableSslVerification()
函数
📑来源
代码源自博客
https://www.cnblogs.com/Springmoon-venn/p/7504901.html
private static void disableSslVerification() {
try
{
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
解析 JSON 字符串形式的返回数据
需先在 Maven 的 pom.xml
加上依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
后在 Java 中引入包
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
并在前文 String res = buffer.toString();
和 return res;
之间添加以下代码
📑来源
代码源自博客
https://blog.csdn.net/qq_43370892/article/details/114805511
//先转换成JSONObject类型
JSONObject jsonObj = JSON.parseObject(str);
//1.通过JSONObject中的getString("key")方法得到对应的值如{"code":"0","error":null,"msg":"success"}这种类型
System.out.println("code"+jsonObj.getString("code"));
//2.字符串中含有数组的下文以array为例
JSONArray jsonInfo = JSONObject.parseArray(jsonObj.getString("array"));//将jsonObj解析成json数组
for (int i = 0; i < jsonInfo.size(); i++) {//遍历数组
JSONObject jsonDetailInfo = jsonInfo.getJSONObject(i);//根据下标以此拿数据每一个数组元素又是一个JSONObject对象所以用JSONObject接收
String x = jsonDetailInfo.getString("x");
String y = jsonDetailInfo.getString("y");
//输出当前获取的数据
System.out.println("x"+x+";y:"+y);
}