版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class doGet {
public static void main(String[] args) {
try {
String path = "访问的接口地址";
URL url = new URL(path);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36");
con.setRequestProperty("Cookie", "shshs..(省略部分)");
con.connect();
if (con.getResponseCode() == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {// 循环读取流
sb.append(line);
}
br.close();// 关闭流
System.out.println(sb);
} else {
System.out.println(con.getResponseCode());
}
con.disconnect();// 断开连接
} catch (Exception e) {
System.out.println(e);
}
}
}
运行代码,返回接口请求结果:
遇到问题:
(1)因系统需要登录,因此调用接口时,需要配置cookie信息,如果不配置cookie,运行会出现如下结果: