1.接收HTTP响应结果(获得字节流,需要转换为字符串):
(1)read方法返回-1代表结束
此方法占用内存大,用来接收网页不适合
InputStream socketIn=socket.getInputStream(); ByteArrayOutputStream buffer=new ByteArrayOutputStream(); byte[]buff=new byte[1024]; int len=-1; while((len=socketIn.read(buff))!=-1){ buffer.write(buff,0,len); } System.out.println(new String(buffer.toByteArray()));
(2)BufferReader方法返回null代表结束
逐行读取网页较适合
InputStream socketIn=socket.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(socketIn)); String data; while((data=br.readLine())!=null){ System.out.println(data); }
2.发送HTTP请求(发送的是字节流)
OutputStream socketOut=socket.getOutputStream(); socketOut.write(sb.toString().getBytes());
3.常用的读写函数
/** *使用如下: PrintWriter pw=getWriter(socket); pw.println("要输出的字符串"); **/ private PrintWriter getWriter(Socket socket)throws IOException{ OutputStream socketOut=socket.getOutputStream(); return new PrintWriter(socketOut,true); } /** *使用如下: BufferedReader br=getReader(socket); String str=br.readLine();//读到的字符串 **/ private BufferedReader getReader(Socket socket)throws IOException{ InputStream socketIn=socket.getInputStream(); return new BufferedReader(new InputStreamReader(socketIn); }