网络编程难题:Java HTTP客户端和服务器端交互案例

原创 痛定思痛。 2024-12-08 06:15 119阅读 0赞

在Java中,实现HTTP客户端和服务器端的交互涉及到Socket编程和HttpURLConnection等技术。以下是一个简单的例子,展示如何创建一个HTTP客户端向服务器发送GET请求。

客户端(使用Java的HttpURLConnection):

  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import javax.net.ssl.HttpsURLConnection;
  4. public class HttpClient {
  5. public static void main(String[] args) throws Exception {
  6. // 创建HTTPS连接
  7. HttpsURLConnection httpsConn = (HttpsURLConnection)
  8. new URL("https://example.com").openConnection();
  9. // 设置请求方法为GET
  10. httpsConn.setRequestMethod("GET");
  11. // 获取并打印响应
  12. int responseCode = httpsConn.getResponseCode();
  13. System.out.println("Response Code : " + responseCode);
  14. BufferedReader in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream())));
  15. String inputLine;
  16. StringBuffer content = new StringBuffer();
  17. while ((inputLine = in.readLine()) != null)) {
  18. content.append(inputLine);
  19. }
  20. in.close();
  21. System.out.println("Response Body : " + content.toString());
  22. }
  23. }

服务器端(使用Java的HttpServer):

  1. import java.io.IOException;
  2. import java.net.ServerSocket;
  3. import java.net.Socket;
  4. public class HttpServer {
  5. public static void main(String[] args) throws IOException {
  6. // 创建服务器监听端口
  7. ServerSocket serverSocket = new ServerSocket(8000);
  8. System.out.println("Http Server is running on port 8000...");
  9. // 等待客户端连接
  10. Socket clientSocket = serverSocket.accept();
  11. System.out.println("Received connection from " + clientSocket.getInetAddress().getHostAddress());
  12. // 客户端发送请求,这里以GET为例
  13. BufferedReader inFromClientSocket = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())));
  14. String inputLine;
  15. StringBuffer content = new StringBuffer();
  16. while ((inputLine = inFromClientSocket.readLine()) != null)) {
  17. content.append(inputLine);
  18. }
  19. // 向客户端发送响应
  20. clientSocket.getOutputStream().write(content.toString());
  21. clientSocket.close();
  22. serverSocket.close();
  23. }
  24. }

这个例子中,客户端使用Java的HttpURLConnection向服务器发送GET请求。服务器端创建一个HttpServer实例监听8000端口,当接收到客户端请求时,返回响应内容。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,119人围观)

还没有评论,来说两句吧...

相关阅读