设置URL
URL obj = new URL("https://www.baidu.com");
创建链接
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
设置参数
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36");
con.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
发出Get请求
con.setRequestMethod("GET");
得到返回请求
int responseCode = con.getResponseCode();
获得url输入流
String responseBody = readResponseBody(con.getInputStream());//这是一个函数
System.out.println(con.getInputStream());
System.out.println(con.getResponseMessage());
System.out.println(responseCode);
System.out.println(con.getContent());
System.out.println(responseBody);
补充
private static String readResponseBody(InputStream inputStream) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
StringBuffer response =new StringBuffer();
while((inputLine = in.readLine()) != null){
response.append(inputLine);
}
in.close();
return response.toString();
}