代码第一行加入以下代理设置。 Fiddler代理的就是8888端口。
System.setProperty("http.proxyHost", "127.0.0.1");
System.setProperty("https.proxyHost", "127.0.0.1");
System.setProperty("http.proxyPort", "8888");
System.setProperty("https.proxyPort", "8888");
get请求工具:
public static byte[] sendGet(String url) {
HttpURLConnection con = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
// 打开连接
con = (HttpURLConnection) new URL(url).openConnection();
// 告诉服务器客户端所支持的压缩方式(然而数据压缩了但没有自动转,就会导致乱码),没有这个头信息说明客户端不支持压缩,要求不压缩直接返回文本
// con.setRequestProperty("Accept-Encoding", "gzip, deflate");//千万不要使用这个请求头,因为我们不会去解压。
con.setRequestProperty("Accept", "application/octet-stream");//二进制流数据
// con.setRequestProperty("Connection", "keep-alive");//抓包发现,不加也是这个
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36");
// con.setRequestProperty("Cookie", cookie);
// 开启连接
con.connect();
is = con.getInputStream();
baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) != -1) {
baos.write(buf, 0, len);
baos.flush();
}
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (baos != null) {
baos.close();
}
if (is != null) {
is.close();
}
if (con != null) {
con.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}