MK
摩柯社区 - 一个极简的技术知识社区
AI 面试

Java使用URLConnection发送请求

2024-07-054.7k 阅读

Java 使用 URLConnection 发送请求基础概念

在 Java 编程中,URLConnection 是一个强大的类,用于与 URL 建立连接并发送请求以及获取响应。它位于 java.net 包中,是一个抽象类,具体的实现依赖于不同的协议。例如,对于 HTTP 协议,HttpURLConnectionURLConnection 的一个重要子类,用于处理 HTTP 相关的请求和响应。

URLConnection 提供了一系列方法来设置请求属性,比如请求头字段,还能获取输出流以向服务器发送数据,获取输入流以读取服务器返回的响应数据。

创建 URL 对象

在使用 URLConnection 发送请求之前,首先需要创建一个 URL 对象。URL 类代表一个统一资源定位符,它是指向互联网“资源”的指针。资源可以是简单的文件或目录,也可以是对更为复杂的对象的引用,例如对数据库或搜索引擎的查询。

下面是创建 URL 对象的示例代码:

import java.net.URL;

public class CreateURLExample {
    public static void main(String[] args) {
        try {
            // 创建一个 URL 对象,指向百度首页
            URL url = new URL("https://www.baidu.com");
            System.out.println("协议: " + url.getProtocol());
            System.out.println("主机: " + url.getHost());
            System.out.println("端口: " + url.getPort());
            System.out.println("路径: " + url.getPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在上述代码中,通过 new URL("https://www.baidu.com") 创建了一个指向百度首页的 URL 对象。然后通过 getProtocol()getHost()getPort()getPath() 方法获取了该 URL 的协议、主机、端口和路径等信息。

获取 URLConnection 对象

创建好 URL 对象后,就可以通过 openConnection() 方法获取 URLConnection 对象。

import java.net.URL;
import java.net.URLConnection;

public class GetURLConnectionExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.example.com");
            // 获取 URLConnection 对象
            URLConnection connection = url.openConnection();
            System.out.println("连接对象类型: " + connection.getClass().getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在这个示例中,通过 url.openConnection() 获取了 URLConnection 对象,并打印出了该对象的类型。在实际的 HTTP 请求场景下,如果 URL 是 HTTP 协议的,返回的连接对象通常是 HttpURLConnection 类型(HttpURLConnectionURLConnection 的子类)。

设置请求属性

URLConnection 允许设置各种请求属性,这些属性通常以键值对的形式存在。常见的请求属性包括 User - AgentContent - TypeAccept 等。

设置 User - Agent

User - Agent 头字段用于标识发起请求的客户端应用程序、操作系统、软件供应商或软件版本。

import java.net.URL;
import java.net.URLConnection;

public class SetUserAgentExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.example.com");
            URLConnection connection = url.openConnection();
            // 设置 User - Agent
            connection.setRequestProperty("User - Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            System.out.println("User - Agent 设置为: " + connection.getRequestProperty("User - Agent"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在上述代码中,通过 connection.setRequestProperty("User - Agent", "具体值") 设置了 User - Agent 属性,并通过 connection.getRequestProperty("User - Agent") 获取并打印了设置的值。

设置 Content - Type

Content - Type 头字段用于指示资源的媒体类型。例如,当发送 JSON 数据时,通常设置为 application/json;发送表单数据时,设置为 application/x - www - form - urlencoded

import java.net.URL;
import java.net.URLConnection;

public class SetContentTypeExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.example.com/api");
            URLConnection connection = url.openConnection();
            // 设置 Content - Type 为 application/json
            connection.setRequestProperty("Content - Type", "application/json");
            System.out.println("Content - Type 设置为: " + connection.getRequestProperty("Content - Type"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这里将 Content - Type 设置为 application/json,表示后续发送的数据格式为 JSON。

发送 GET 请求

GET 请求是最常见的 HTTP 请求方法之一,用于从服务器获取资源。使用 URLConnection 发送 GET 请求相对简单,因为默认情况下,URLConnection 发起的请求就是 GET 请求。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class SendGETRequestExample {
    public static void main(String[] args) {
        try {
            // 创建 URL 对象
            URL url = new URL("https://www.example.com/api?param1=value1&param2=value2");
            // 获取 URLConnection 对象
            URLConnection connection = url.openConnection();
            // 设置请求方法为 GET(实际上默认就是 GET,可以不设置)
            connection.setRequestMethod("GET");
            // 获取输入流以读取响应数据
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            // 打印响应数据
            System.out.println("响应内容: " + response.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在上述代码中,首先创建了一个包含参数的 URL。然后获取 URLConnection 对象,并设置请求方法为 GET(虽然默认就是 GET,但明确设置可以增强代码可读性)。接着通过 connection.getInputStream() 获取输入流,使用 BufferedReader 逐行读取响应数据并存储在 StringBuilder 中,最后打印出响应内容。

发送 POST 请求

POST 请求通常用于向服务器提交数据,比如提交表单数据或 JSON 数据。与 GET 请求不同,POST 请求的数据通常放在请求体中。

发送表单数据

发送表单数据时,数据需要按照 application/x - www - form - urlencoded 格式进行编码。

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class SendPOSTFormDataExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.example.com/api/submit");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content - Type", "application/x - www - form - urlencoded");
            connection.setDoOutput(true);

            // 构建表单数据
            Map<String, String> formData = new HashMap<>();
            formData.put("username", "testuser");
            formData.put("password", "testpassword");
            StringBuilder postData = new StringBuilder();
            for (Map.Entry<String, String> param : formData.entrySet()) {
                if (postData.length() != 0) postData.append('&');
                postData.append(URLEncoder.encode(param.getKey(), "UTF - 8"));
                postData.append('=');
                postData.append(URLEncoder.encode(param.getValue(), "UTF - 8"));
            }
            byte[] postDataBytes = postData.toString().getBytes("UTF - 8");

            // 发送表单数据
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.write(postDataBytes);
            wr.flush();
            wr.close();

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

            // 打印响应数据
            System.out.println("响应内容: " + response.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在这段代码中,首先创建了一个 HttpURLConnection 对象(因为是 HTTP POST 请求),设置请求方法为 POST,并设置 Content - Typeapplication/x - www - form - urlencoded。然后构建表单数据,将数据进行 URL 编码并拼接成字符串。通过 connection.getOutputStream() 获取输出流,将编码后的数据写入输出流发送到服务器。最后读取服务器的响应数据并打印。

发送 JSON 数据

发送 JSON 数据时,Content - Type 需要设置为 application/json

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class SendPOSTJSONDataExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.example.com/api/json");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content - Type", "application/json");
            connection.setDoOutput(true);

            // 构建 JSON 数据
            String jsonInputString = "{\"name\":\"John\",\"age\":30}";

            // 发送 JSON 数据
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(jsonInputString);
            wr.flush();
            wr.close();

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

            // 打印响应数据
            System.out.println("响应内容: " + response.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

此代码设置 Content - Typeapplication/json,然后构建一个简单的 JSON 字符串,并通过输出流将其发送到服务器。最后读取并打印服务器的响应。

处理响应

无论是 GET 请求还是 POST 请求,服务器都会返回一个响应。URLConnection 提供了多种方法来处理这个响应。

获取响应码

HTTP 响应码表示请求的处理结果。常见的响应码有 200(成功)、404(未找到资源)、500(服务器内部错误)等。

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class GetResponseCodeExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.example.com");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();
            System.out.println("响应码: " + responseCode);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在上述代码中,通过 connection.getResponseCode() 获取了服务器返回的响应码并打印。

获取响应头

响应头包含了关于响应的元信息,例如 Content - LengthDate 等。

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class GetResponseHeadersExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.example.com");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            Map<String, List<String>> headers = connection.getHeaderFields();
            for (String key : headers.keySet()) {
                System.out.println(key + ": " + headers.get(key));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这里通过 connection.getHeaderFields() 获取了所有的响应头信息,并通过循环打印出每个头字段及其对应的值。

读取响应体

前面的示例中已经展示了如何通过 BufferedReaderInputStreamReader 从输入流中读取响应体数据。但需要注意的是,当请求失败(例如响应码为 404 或 500)时,getInputStream() 会抛出异常。此时应该使用 getErrorStream() 来读取错误信息。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class ReadResponseBodyExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.example.com/nonexistentpage");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();
            if (responseCode >= 200 && responseCode < 300) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                System.out.println("成功响应内容: " + response.toString());
            } else {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
                String inputLine;
                StringBuilder errorResponse = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    errorResponse.append(inputLine);
                }
                in.close();
                System.out.println("错误响应内容: " + errorResponse.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在这个示例中,根据响应码判断请求是否成功。如果成功,从 getInputStream() 读取响应体;如果失败,从 getErrorStream() 读取错误信息。

处理连接超时

在网络请求过程中,可能会因为网络问题导致请求长时间无响应。为了避免程序一直等待,可以设置连接超时和读取超时。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class SetTimeoutExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.example.com");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            // 设置连接超时时间为 5 秒
            connection.setConnectTimeout(5000);
            // 设置读取超时时间为 10 秒
            connection.setReadTimeout(10000);
            int responseCode = connection.getResponseCode();
            if (responseCode >= 200 && responseCode < 300) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                System.out.println("响应内容: " + response.toString());
            } else {
                System.out.println("请求失败,响应码: " + responseCode);
            }
        } catch (IOException e) {
            System.out.println("发生异常: " + e.getMessage());
        }
    }
}

在上述代码中,通过 connection.setConnectTimeout(5000) 设置连接超时时间为 5 秒,通过 connection.setReadTimeout(10000) 设置读取超时时间为 10 秒。如果在规定时间内连接未建立或数据未读取完成,会抛出 IOException,在 catch 块中可以进行相应处理。

处理重定向

在 HTTP 请求中,服务器可能会返回重定向响应(例如 301 永久重定向或 302 临时重定向)。HttpURLConnection 可以自动处理重定向,但也可以手动控制。

自动处理重定向

默认情况下,HttpURLConnection 会自动处理重定向。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class AutoRedirectExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://www.example.com/redirect");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();
            if (responseCode >= 200 && responseCode < 300) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                System.out.println("最终响应内容: " + response.toString());
            } else {
                System.out.println("请求失败,响应码: " + responseCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在这个示例中,如果服务器返回重定向响应,HttpURLConnection 会自动跟随重定向,最终获取到重定向后的资源内容。

手动处理重定向

如果想要手动处理重定向,可以设置 HttpURLConnectionInstanceFollowRedirects 属性为 false

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class ManualRedirectExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://www.example.com/redirect");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setInstanceFollowRedirects(false);
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                String redirectUrl = connection.getHeaderField("Location");
                System.out.println("重定向到: " + redirectUrl);
                // 手动发起新的请求
                URL newUrl = new URL(redirectUrl);
                HttpURLConnection newConnection = (HttpURLConnection) newUrl.openConnection();
                newConnection.setRequestMethod("GET");
                int newResponseCode = newConnection.getResponseCode();
                if (newResponseCode >= 200 && newResponseCode < 300) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(newConnection.getInputStream()));
                    String inputLine;
                    StringBuilder response = new StringBuilder();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                    System.out.println("重定向后响应内容: " + response.toString());
                } else {
                    System.out.println("重定向后请求失败,响应码: " + newResponseCode);
                }
            } else {
                System.out.println("未发生重定向,响应码: " + responseCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在上述代码中,首先将 connection.setInstanceFollowRedirects(false) 设置为手动处理重定向。当获取到重定向响应码(301 或 302)时,从响应头中获取重定向的 URL,然后手动创建新的连接并发起请求,获取重定向后的资源内容。

高级应用:处理 Cookie

在 Web 开发中,Cookie 用于在客户端和服务器之间传递少量数据。HttpURLConnection 可以通过设置和读取 Cookie 头字段来处理 Cookie。

设置 Cookie

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class SetCookieExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.example.com/api");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content - Type", "application/json");
            connection.setRequestProperty("Cookie", "username=testuser; sessionid=12345");
            connection.setDoOutput(true);

            // 构建 JSON 数据
            String jsonInputString = "{\"name\":\"John\",\"age\":30}";

            // 发送 JSON 数据
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(jsonInputString);
            wr.flush();
            wr.close();

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

            // 打印响应数据
            System.out.println("响应内容: " + response.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在这段代码中,通过 connection.setRequestProperty("Cookie", "具体 cookie 内容") 设置了 Cookie 头字段,将 Cookie 发送到服务器。

读取 Cookie

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class ReadCookieExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.example.com");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            List<String> cookies = connection.getHeaderFields().get("Set - Cookie");
            if (cookies != null) {
                for (String cookie : cookies) {
                    System.out.println("收到的 Cookie: " + cookie);
                }
            }
            // 读取响应数据
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            // 打印响应数据
            System.out.println("响应内容: " + response.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

此代码通过 connection.getHeaderFields().get("Set - Cookie") 获取服务器返回的 Cookie 信息,并进行打印。

安全性考虑

在使用 URLConnection 发送请求时,安全性是一个重要的考量因素。

使用 HTTPS

当发送敏感数据时,应使用 HTTPS 协议。HttpURLConnection 对 HTTPS 有很好的支持。

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HTTPSExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.example.com/api");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content - Type", "application/json");
            connection.setDoOutput(true);

            // 构建 JSON 数据
            String jsonInputString = "{\"name\":\"John\",\"age\":30}";

            // 发送 JSON 数据
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(jsonInputString);
            wr.flush();
            wr.close();

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

            // 打印响应数据
            System.out.println("响应内容: " + response.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在这个示例中,URL 使用了 https 协议,HttpURLConnection 会自动处理 HTTPS 连接的建立和加密通信。

证书验证

在 HTTPS 连接中,客户端需要验证服务器的证书。默认情况下,Java 会使用系统信任的证书颁发机构(CA)来验证服务器证书。但在某些情况下,可能需要自定义证书验证逻辑,例如在开发环境中使用自签名证书。

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class CustomCertificateValidationExample {
    public static void main(String[] args) {
        try {
            // 创建信任所有证书的 TrustManager
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[0];
                        }
                    }
            };

            // 创建 SSLContext 并初始化
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new SecureRandom());

            // 创建 HttpsURLConnection 并设置 SSLContext
            URL url = new URL("https://www.example.com/api");
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setSSLSocketFactory(sslContext.getSocketFactory());

            // 创建 HostnameVerifier 并设置
            HostnameVerifier allHostsValid = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
            connection.setHostnameVerifier(allHostsValid);

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content - Type", "application/json");
            connection.setDoOutput(true);

            // 构建 JSON 数据
            String jsonInputString = "{\"name\":\"John\",\"age\":30}";

            // 发送 JSON 数据
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(jsonInputString);
            wr.flush();
            wr.close();

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

            // 打印响应数据
            System.out.println("响应内容: " + response.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在上述代码中,创建了一个信任所有证书的 TrustManager,并使用它初始化 SSLContext。然后设置 HttpsURLConnection 使用这个 SSLContext。同时,创建了一个验证所有主机名的 HostnameVerifier 并设置给 HttpsURLConnection。这样在开发环境中就可以绕过自签名证书的验证问题,但在生产环境中应谨慎使用,因为这种方式会降低安全性。

通过以上详细的介绍和丰富的代码示例,相信你已经对 Java 使用 URLConnection 发送请求有了深入的理解,可以在实际项目中灵活运用这些知识来实现各种网络请求功能。