<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
代码:
public class Test {
public static void main(String[] args) {
System.out.println(doGet("http://www.baidu.com"));
}
/**
* 测试get请求方式
*
* @param apiUrl 链接
* @return 请求返回值
* @author 明快de玄米61
* @date 2021/09/05
*/
private static String doGet(String apiUrl) {
HttpURLConnection connection = null;
InputStream in = null;
BufferedReader reader = null;
try {
// 构造一个URL对象
URL url = new URL(apiUrl);
// 获取URLConnection对象
connection = (HttpURLConnection) url.openConnection();
// getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法,所以在开发中不调用connect()也可以)
in = connection.getInputStream();
// 通过InputStreamReader将字节流转换成字符串,在通过BufferedReader将字符流转换成自带缓冲流
reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
String line = null;
// 按行读取
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
// 关闭连接和流
if (connection != null) {
connection.disconnect();
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
结果:
<!DOCTYPE html><!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129>