public static void main(String[] args) throws Exception {
String str = "http://www.baidu.com";
URL url = new URL(str);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line ="";
while ((line = bufferedReader.readLine()) != null){
stringBuffer.append(line).append("\r\n");
}
System.out.println("HTTP Response Code=======>"+connection.getResponseCode());
System.out.println("HTTP Response =======>"+stringBuffer);
}
- 设置url对象,java.net的包里的。
- 创建连接url.openConnection,HttpURLConnection 来接
- 创建输入流接受响应
期间还遇到了这个问题,原因也很简单就是链接忘记加http:// 人家不知道什么协议了。