java socket实现http请求

本文介绍了一个简单的HTTP客户端实现方法,通过自定义MyStreamSocket类来发送HTTP请求并接收响应。该客户端能够连接到指定主机和端口,发送GET请求,并打印从服务器接收到的所有响应信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

应用逻辑层:
import java.net.*;
import java.io.*;

public class MyStreamSocket extends Socket {
   private Socket  socket;
   private BufferedReader input;
   private PrintWriter output;

   MyStreamSocket(String acceptorHost,
                  int acceptorPort ) throws SocketException,
                                   IOException{
      socket = new Socket(acceptorHost, acceptorPort );
      setStreams( );
   }

   MyStreamSocket(Socket socket)  throws IOException {
      this.socket = socket;
      setStreams( );
   }

   private void setStreams( ) throws IOException{
      // get an input stream for reading from the data socket
      InputStream inStream = socket.getInputStream();
      input = 
         new BufferedReader(new InputStreamReader(inStream));
      OutputStream outStream = socket.getOutputStream();
      // create a PrinterWriter object for character-mode output
      output = 
         new PrintWriter(new OutputStreamWriter(outStream));
   }

   public void sendMessage(String message)
             throws IOException {
      output.println(message);   
      //The ensuing flush method call is necessary for the data to
      // be written to the socket data stream before the
      // socket is closed.
      output.flush();               
   } // end sendMessage

   public String receiveMessage( )
throws IOException {
      // read a line from the data stream
      String message = input.readLine( );  
      return message;
   } //end receiveMessage

   public void close( )
throws IOException {
      socket.close( );
   }
} //end class

//界面层?

public class HTTPClient {

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String host = "www.baidu.com"/*args[0]*/;
int port = 80/*Integer.parseInt(args[1])*/;
String fileName = "/index.html"/*args[2].trim()*/;
String request = "GET " + fileName +" HTTP/1.0\r\n";//Http请求行。具体百度谷歌之。
MyStreamSocket mySocket = new MyStreamSocket(host,port);
//System.out.println("connection made!");
mySocket.sendMessage(request);
String response;
response = mySocket.receiveMessage();
while (response != null) {
System.out.println(response);//打印服务器响应信息。包括状态行。头部内容。空行。web对象内容。
response = mySocket.receiveMessage(); 
}
} catch (Exception e) {
// TODO: handle exception
}
}
}

//运行后的响应信息


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值