1、在pom.xml中添加依赖包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
2、创建测试类(HttpURLconnectionTest3.java)
package com.jeff;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeff.entity.SysUser;
public class HttpURLconnectionTest3 {
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:8080/getUserList");
// 得到connection对象。
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置网络连接超时时间
connection.setConnectTimeout(3000);
// 设置请求方式
connection.setRequestMethod("POST");
// 允许写出
connection.setDoOutput(true);
// 允许读入
connection.setDoInput(true);
// 不使用缓存
connection.setUseCaches(false);
// 连接
connection.connect();
// 得到响应码
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 得到响应流
InputStream inputStream = connection.getInputStream();
// 将响应流转换成字符串
String jsonStr = inputStreamToString(inputStream);
if (StringUtils.isNotBlank(jsonStr)) {
JSONObject jsonObject = JSON.parseObject(jsonStr);
Long total = jsonObject.getLong("total");
Integer code = jsonObject.getInteger("code");
System.out.println("total:" + total + ",code:" + code);
JSONArray results = jsonObject.getJSONArray("results");
if (results.size() > 0) {
for (int i = 0; i < results.size(); i++) {
// 遍历 jsonArray 数组,把每一个对象转成 json 对象
JSONObject job = results.getJSONObject(i);
SysUser user = JSONObject.toJavaObject(job, SysUser.class);
System.out.println(user.toString());
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @description: 将输入流转换成字符串
* @author: Jeff
* @date: 2019年12月15日
* @param inputStream 输入流
* @return
*/
private static String inputStreamToString(InputStream inputStream) {
StringBuffer buffer = new StringBuffer();
InputStreamReader inputStreamReader;
try {
inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer.toString();
}
}
3、控制台输出结果