public static void test() throws Exception { // http://127.0.0.1:8080/logger/user InetAddress inetAddress = InetAddress.getByName("www.baidu.com"); Socket socket = new Socket(inetAddress.getHostAddress(), 80); if (socket.isConnected()) { System.out.println("连接建立,远程地址:" + socket.getRemoteSocketAddress()); } // 关键!此处在Socket的输出流写入HTTP的GET报文,请服务器做出响应。 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); bw.write("GET / HTTP/1.1\r\n"); bw.write("Host: www.baidu.com\r\n"); bw.write("\r\n"); bw.flush(); // 开始读取远程服务器的响应数据。 BufferedInputStream bis = new BufferedInputStream(socket.getInputStream()); byte[] buffer = new byte[1024]; int count = 0; StringBuilder sb = new StringBuilder(); while (true) { count = bis.read(buffer); if (count == -1) { break; } sb.append(new String(buffer, 0, count, "UTF-8")); } System.out.printf("sb:"+sb.toString()); bw.close(); bis.close(); socket.close(); } public static void test2() throws Exception { URL url = new URL("http://127.0.0.1:8080/logger/user"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); // 开始读取远程服务器的响应数据。 BufferedInputStream bis = new BufferedInputStream(urlConnection.getInputStream()); StringBuilder sb = new StringBuilder(); byte[] buffer = new byte[1024 * 10]; int count = 0; while (true) { count = bis.read(buffer); if (count == -1) { break; } sb.append(new String(buffer, 0, count, "UTF-8")); } System.out.printf(""+sb.toString()); bis.close(); }
标签:count,http,socket,buffer,bw,sb,new,httpURLConnection From: https://www.cnblogs.com/niun/p/17217970.html