Administrator
发布于 2023-11-23 / 25 阅读
0
0

URLConnection详解

Socket 发送HTTP请求示例(原始)

1.创建socket ,同时建立连接: Socket socket = new Socket(host, port);

2.获取socket的InputStream,并写入请求行、请求头、请求体 ;

3.获取socket的OutputStream,获取到相应行、相应头、相应体 ;

4.关闭资源

import java.io.*;
import java.net.Socket;

public class SocketExample {
    public static void main(String[] args) {
        String host = "example.com";
        int port = 80;
        String path = "/abc";
        String httpPostData = "key1=value1&key2=value2";

        try {
            // 建立套接字连接
            Socket socket = new Socket(host, port);

            String httpPostRequest = "POST http://" + host + path + " HTTP/1.1\r\n" +
                    "Host: " + host + "\r\n" +
                    "Content-Type: application/x-www-form-urlencoded\r\n" +
                    "Content-Length: " + httpPostData.length() + "\r\n" +
                    "\r\n" +
                    httpPostData;

            // 发送 HTTP POST 请求
            OutputStream out = socket.getOutputStream();
            out.write(httpPostRequest.getBytes());
            out.flush();


            // 创建输入流,读取服务器响应
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }

            // 关闭流和套接字连接
            in.close();
            out.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

如下,请求内容

POST http://example.com/abc HTTP/1.1

Host: example.com

Content-Type: application/x-www-form-urlencoded

Content-Length: 23

key1=value1&key2=value2

如下,响应内容

HTTP/1.0 400 Bad Request

Content-Type: text/html

Content-Length: 349

Connection: close

Date: Thu, 23 Nov 2023 02:36:15 GMT

Server: ECSF (sed/58EA)

<?xml version="1.0" encoding="iso-8859-1"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

<title>400 - Bad Request</title>

</head>

<body>

<h1>400 - Bad Request</h1>

</body>

</html>

URL.openConnection()示例

1.创建URL对象

2.打开一个connection连接

3.设置请求方法,GET

4.发送请求,获取请求码和状态

5.获取请求体

6.连接关闭

public class HttpClientExample {
    public static void main(String[] args) {
        String urlString = "http://example.com/";

        try {
            // 创建 URL 对象
            URL url = new URL(urlString);

            // 打开 HTTP 连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为 GET
            connection.setRequestMethod("GET");

            // 发送请求并获取响应状态码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
			//获取请求状态
            String message = connection.getResponseMessage() ;
            System.out.printf("message "+message+"\n");

            // 读取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = in.readLine()) != null) {
                response.append(line);
            }
            in.close();

            // 打印响应内容
            System.out.println("Response:");
            System.out.println(response.toString());

            // 关闭连接
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

小结:

上面内容也是建立连接,发送请求行,请求头,请求体;服务器回应响应行,相应头,响应体

URL.openConnection()解析


评论