相应内容格式 gzip
package com.bonc.mine.common.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.GZIPInputStream;
/**
* Created on 2022/3/16.
*
* @author lichuanming
*
* 发送 get请求,针对gizp
*/
public class SendGetUntil {
public static String sendGet(String url) {
StringBuffer stringBuffer = new StringBuffer();
try {
URL realUrl = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection) realUrl.openConnection();
//在这里设置一些属性,详细见UrlConnection文档,HttpURLConnection是UrlConnection的子类
//设置连接超时为5秒
httpURLConnection.setConnectTimeout(5000);
//设定请求方式(默认为get)
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("accept", "*/*");
httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8");
httpURLConnection.setRequestProperty("contentType", "UTF-8");
httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
//建立到远程对象的实际连接
httpURLConnection.connect();
GZIPInputStream gZIPInputStream = null;
String encoding = httpURLConnection.getContentEncoding();
if(encoding.equals("gzip")){
gZIPInputStream = new GZIPInputStream(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gZIPInputStream));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
//转化为UTF-8的编码格式
line = new String(line.getBytes("UTF-8"));
stringBuffer.append(line);
}
bufferedReader.close();
}else{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
//转化为UTF-8的编码格式
line = new String(line.getBytes("UTF-8"));
stringBuffer.append(line);
}
bufferedReader.close();
}
//返回打开连接读取的输入流,输入流转化为StringBuffer类型,这一套流程要记住,常用
httpURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuffer.toString();
}
}
不恋尘世浮华,不写红尘纷扰
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理