当前位置: 首页 > news >正文

【Java】实现后端请求接口

【Java】实现后端请求接口

  • 【一】使用 HttpURLConnection 实现四种请求方式的示例
    • 【1】Get请求
    • 【2】POST请求
    • 【3】PUT请求
    • 【4】DELETE 请求
    • 【5】汇总工具类,通过传参实现4种请求
  • 【二】HttpClient 实现四种请求方式的示例
    • 【1】GET请求
    • 【2】POST 请求
    • 【3】PUT 请求
    • 【4】DELETE 请求
    • 【5】汇总的工具类

【一】使用 HttpURLConnection 实现四种请求方式的示例

HttpURLConnection 是 Java 标准库中较早提供的 HTTP 请求工具

【1】Get请求

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

public class HttpGetExample {
    public static String sendGet(String urlStr) throws Exception {
        // 对 URL 中的中文参数进行编码
        String encodedUrl = URLEncoder.encode(urlStr, "UTF-8").replaceAll("\\+", "%20");
        URL url = new URL(encodedUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        // 设置请求头,指定接收的字符编码
        connection.setRequestProperty("Accept-Charset", "UTF-8");

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 使用 BufferedReader 读取响应内容,并指定字符编码为 UTF-8
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            return response.toString();
        }
        return null;
    }

    public static void main(String[] args) {
        try {
            String url = "http://example.com/api?param=中文参数";
            String response = sendGet(url);
            System.out.println(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

【2】POST请求

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

public class HttpPostExample {
    public static String sendPost(String urlStr, String params) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置请求头,指定字符编码和内容类型
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        connection.setRequestProperty("Accept-Charset", "UTF-8");
        connection.setDoOutput(true);

        // 对请求参数进行编码
        String encodedParams = URLEncoder.encode(params, "UTF-8");
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(encodedParams);
        outputStream.flush();
        outputStream.close();

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 使用 BufferedReader 读取响应内容,并指定字符编码为 UTF-8
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            return response.toString();
        }
        return null;
    }

    public static void main(String[] args) {
        try {
            String url = "http://example.com/api";
            String params = "param=中文参数";
            String response = sendPost(url, params);
            System.out.println(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

【3】PUT请求

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

public class HttpPutExample {
    public static String sendPut(String urlStr, String params) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("PUT");
        // 设置请求头,指定字符编码和内容类型
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        connection.setRequestProperty("Accept-Charset", "UTF-8");
        connection.setDoOutput(true);

        // 对请求参数进行编码
        String encodedParams = URLEncoder.encode(params, "UTF-8");
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(encodedParams);
        outputStream.flush();
        outputStream.close();

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 使用 BufferedReader 读取响应内容,并指定字符编码为 UTF-8
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            return response.toString();
        }
        return null;
    }

    public static void main(String[] args) {
        try {
            String url = "http://example.com/api";
            String params = "param=中文参数";
            String response = sendPut(url, params);
            System.out.println(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

【4】DELETE 请求

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

public class HttpDeleteExample {
    public static String sendDelete(String urlStr) throws Exception {
        // 对 URL 中的中文参数进行编码
        String encodedUrl = URLEncoder.encode(urlStr, "UTF-8").replaceAll("\\+", "%20");
        URL url = new URL(encodedUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("DELETE");
        // 设置请求头,指定接收的字符编码
        connection.setRequestProperty("Accept-Charset", "UTF-8");

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 使用 BufferedReader 读取响应内容,并指定字符编码为 UTF-8
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            return response.toString();
        }
        return null;
    }

    public static void main(String[] args) {
        try {
            String url = "http://example.com/api?param=中文参数";
            String response = sendDelete(url);
            System.out.println(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

【5】汇总工具类,通过传参实现4种请求

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

public class HttpUtils {
    public static String sendRequest(String urlStr, String method, String params) {
        try {
            URL url;
            if (method.equalsIgnoreCase("GET") || method.equalsIgnoreCase("DELETE")) {
                if (params != null) {
                    urlStr += "?" + URLEncoder.encode(params, "UTF-8").replaceAll("\\+", "%20");
                }
                url = new URL(urlStr);
            } else {
                url = new URL(urlStr);
            }
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(method);
            // 设置请求头,指定字符编码和接收内容的字符编码
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            connection.setRequestProperty("Accept-Charset", "UTF-8");

            if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) {
                connection.setDoOutput(true);
                if (params != null) {
                    String encodedParams = URLEncoder.encode(params, "UTF-8");
                    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
                    outputStream.writeBytes(encodedParams);
                    outputStream.flush();
                    outputStream.close();
                }
            }

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 使用 BufferedReader 读取响应内容,并指定字符编码为 UTF-8
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                return response.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String url = "http://example.com/api";
        String params = "param=中文参数";

        String getResponse = sendRequest(url, "GET", params);
        System.out.println("GET Response: " + getResponse);

        String postResponse = sendRequest(url, "POST", params);
        System.out.println("POST Response: " + postResponse);

        String putResponse = sendRequest(url, "PUT", params);
        System.out.println("PUT Response: " + putResponse);

        String deleteResponse = sendRequest(url + "?" + params, "DELETE", null);
        System.out.println("DELETE Response: " + deleteResponse);
    }
}

【二】HttpClient 实现四种请求方式的示例

HttpClient 是 Java 11 及以上版本引入的新的 HTTP 客户端,使用起来更加简洁和方便。

【1】GET请求

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HttpClientGetExample {
    public static void main(String[] args) {
        try {
            // 创建 HttpClient 实例
            HttpClient client = HttpClient.newHttpClient();
            // 构建 GET 请求,指定请求 URL
            HttpRequest request = HttpRequest.newBuilder()
                   .uri(URI.create("https://example.com/api?param=中文参数"))
                   .header("Accept-Charset", "UTF-8") // 设置接收响应的字符编码为 UTF-8
                   .GET()
                   .build();
            // 发送请求并获取响应,指定响应体处理方式为按 UTF-8 编码读取字符串
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println("Status code: " + response.statusCode());
            System.out.println("Response body: " + response.body());
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

【2】POST 请求

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class HttpClientPostExample {
    public static void main(String[] args) {
        try {
            // 构建请求体,对中文参数进行编码
            String param = URLEncoder.encode("中文参数", StandardCharsets.UTF_8);
            String requestBody = "param=" + param;
            // 创建 HttpClient 实例
            HttpClient client = HttpClient.newHttpClient();
            // 构建 POST 请求,设置请求头的字符编码和内容类型
            HttpRequest request = HttpRequest.newBuilder()
                   .uri(URI.create("https://example.com/api"))
                   .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                   .header("Accept-Charset", "UTF-8")
                   .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                   .build();
            // 发送请求并获取响应,指定响应体处理方式为按 UTF-8 编码读取字符串
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println("Status code: " + response.statusCode());
            System.out.println("Response body: " + response.body());
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

【3】PUT 请求

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class HttpClientPutExample {
    public static void main(String[] args) {
        try {
            // 构建请求体,对中文参数进行编码
            String param = URLEncoder.encode("中文参数", StandardCharsets.UTF_8);
            String requestBody = "param=" + param;
            // 创建 HttpClient 实例
            HttpClient client = HttpClient.newHttpClient();
            // 构建 PUT 请求,设置请求头的字符编码和内容类型
            HttpRequest request = HttpRequest.newBuilder()
                   .uri(URI.create("https://example.com/api"))
                   .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                   .header("Accept-Charset", "UTF-8")
                   .PUT(HttpRequest.BodyPublishers.ofString(requestBody))
                   .build();
            // 发送请求并获取响应,指定响应体处理方式为按 UTF-8 编码读取字符串
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println("Status code: " + response.statusCode());
            System.out.println("Response body: " + response.body());
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

【4】DELETE 请求

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HttpClientDeleteExample {
    public static void main(String[] args) {
        try {
            // 创建 HttpClient 实例
            HttpClient client = HttpClient.newHttpClient();
            // 构建 DELETE 请求,指定请求 URL 和接收响应的字符编码
            HttpRequest request = HttpRequest.newBuilder()
                   .uri(URI.create("https://example.com/api?param=中文参数"))
                   .header("Accept-Charset", "UTF-8")
                   .DELETE()
                   .build();
            // 发送请求并获取响应,指定响应体处理方式为按 UTF-8 编码读取字符串
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println("Status code: " + response.statusCode());
            System.out.println("Response body: " + response.body());
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

【5】汇总的工具类

HttpClientUtils 类中的 sendRequest 方法根据传入的 url、method 和 requestBody 构建相应的 HttpRequest 对象并发送请求。对于 GET 和 DELETE 请求,requestBody 可以传入 null;对于 POST 和 PUT 请求,需要传入请求体内容。在 main 方法中演示了如何调用该工具类的方法进行不同类型的请求。

(1)在请求头中设置 Accept-Charset 为 UTF-8,告诉服务器客户端期望接收的字符编码。
(2)对于 POST 和 PUT 请求,使用 URLEncoder 对请求体中的中文参数进行编码,避免发送时出现乱码。
(3)使用 HttpResponse.BodyHandlers.ofString() 接收响应体,默认以 UTF - 8 编码读取字符串。

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class HttpClientUtils {
    private static final HttpClient client = HttpClient.newHttpClient();

    public static String sendRequest(String url, String method, String requestBody) {
        try {
            HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                   .uri(URI.create(url))
                   .header("Accept-Charset", "UTF-8");

            switch (method.toUpperCase()) {
                case "GET":
                    requestBuilder.GET();
                    break;
                case "POST":
                    if (requestBody != null) {
                        requestBody = URLEncoder.encode(requestBody, StandardCharsets.UTF_8);
                    }
                    requestBuilder.header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                           .POST(HttpRequest.BodyPublishers.ofString(requestBody));
                    break;
                case "PUT":
                    if (requestBody != null) {
                        requestBody = URLEncoder.encode(requestBody, StandardCharsets.UTF_8);
                    }
                    requestBuilder.header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                           .PUT(HttpRequest.BodyPublishers.ofString(requestBody));
                    break;
                case "DELETE":
                    requestBuilder.DELETE();
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported HTTP method: " + method);
            }

            HttpRequest request = requestBuilder.build();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            return response.body();
        } catch (IOException | InterruptedException | IllegalArgumentException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String getUrl = "https://example.com/api?param=中文参数";
        String postUrl = "https://example.com/api";
        String putUrl = "https://example.com/api";
        String deleteUrl = "https://example.com/api?param=中文参数";
        String postBody = "param=中文参数";
        String putBody = "param=中文参数";

        System.out.println("GET response: " + sendRequest(getUrl, "GET", null));
        System.out.println("POST response: " + sendRequest(postUrl, "POST", postBody));
        System.out.println("PUT response: " + sendRequest(putUrl, "PUT", putBody));
        System.out.println("DELETE response: " + sendRequest(deleteUrl, "DELETE", null));
    }
}

相关文章:

  • 组合的输出(信息学奥赛一本通-1317)
  • 关于防火墙运维面试题2
  • DirectShow基类文件和帮助文档
  • 【无标题】基于AIX的DB2 10.1安装配置规范
  • Qt的QTreeWidget样式设置
  • Linux进阶——防火墙
  • 【鸿蒙开发】第三十章 应用稳定性-检测、分析、优化、运维汇总
  • 数据结构——二叉树(2025.2.12)
  • 用大模型学大模型04-模型与网络
  • 负载测试和压力测试的原理分别是什么
  • 代码实践——准备阶段
  • Linux 系统上以 root 用户身份运行 ./mysql.server start 命令,但仍然收到 “Permission denied” 错误
  • Spring Cloud微服务
  • 【CS61A 2024秋】Python入门课,全过程记录P7(Week13 Macros至完结)【完结撒花!】
  • 新一代高性能无线传输模块M-GATEWAY3
  • 玩转观察者模式
  • 【Linux】进程间关系与守护进程
  • MySQL 记录
  • c# textbox 设置不获取光标
  • 微信小程序 - 组件和样式
  • 科普|认识谵妄:它有哪些表现?患者怎样走出“迷雾”?
  • 对谈|“大礼议”:嘉靖皇帝的礼法困境与权力博弈
  • 大环线呼之欲出,“金三角”跑起来了
  • 四川内江警方通报一起持刀伤人致死案:因车辆停放引起,嫌犯被抓获
  • 龚正会见哥伦比亚总统佩特罗
  • 共建医学人工智能高地,上海卫健委与徐汇区将在这些方面合作