使用 Java 11+ HttpClient 和 Apache HttpClient 设置HTTP请求参数的方法

使用 Java 11+ HttpClient 设置请求参数

从Java 11开始,Java自带的HttpClient可以方便地发送HTTP请求。以下是如何设置GET和POST请求参数的示例:

GET 请求

对于GET请求,参数通常通过URL拼接的方式传递:

java 复制代码
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Java11HttpClientExample {
    public static void main(String[] args) {
        String baseUrl = "https://api.example.com/data";
        String param1 = "value1";
        String param2 = "value2";

        // 构建带参数的URL
        String fullUrl = baseUrl + "?param1=" + param1 + "&param2=" + param2;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(fullUrl))
                .GET()
                .build();

        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println("Response: " + response.body());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

POST 请求

对于POST请求,参数可以通过请求体传递:

java 复制代码
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Java11HttpClientPostExample {
    public static void main(String[] args) {
        String url = "https://api.example.com/data";
        String jsonBody = "{\"param1\":\"value1\", \"param2\":\"value2\"}";

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
                .build();

        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println("Response: " + response.body());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

使用 Apache HttpClient 设置请求参数

Apache HttpClient 是一个功能强大的第三方库,可以用来发送HTTP请求。以下是如何设置GET和POST请求参数的示例:

GET 请求

对于GET请求,可以使用URIBuilder来构建带参数的URL:

java 复制代码
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.net.URI;

public class ApacheHttpClientExample {
    public static void main(String[] args) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            URI uri = new URIBuilder()
                    .setScheme("http")
                    .setHost("example.com")
                    .setPath("/api/data")
                    .setParameter("param1", "value1")
                    .setParameter("param2", "value2")
                    .build();

            HttpGet httpGet = new HttpGet(uri);
            httpGet.setHeader("Content-Type", "application/json");

            httpClient.execute(httpGet);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

POST 请求

对于POST请求,可以通过HttpPostStringEntity来设置请求体:

java 复制代码
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class ApacheHttpClientPostExample {
    public static void main(String[] args) {
        String url = "https://api.example.com/data";
        String jsonBody = "{\"param1\":\"value1\", \"param2\":\"value2\"}";

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/json");

            StringEntity entity = new StringEntity(jsonBody, "UTF-8");
            httpPost.setEntity(entity);

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                String responseBody = EntityUtils.toString(response.getEntity());
                System.out.println("Response: " + responseBody);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

注意事项

  1. 参数编码 :在设置请求参数时,确保对参数值进行适当的编码,以避免特殊字符导致的问题。可以使用java.net.URLEncoder来对参数值进行编码。

  2. 请求头设置 :根据目标API的要求,设置适当的请求头,例如User-AgentContent-Type等。

  3. 错误处理:在发送请求时,添加适当的错误处理逻辑,以确保程序的健壮性。

通过上述示例代码,你可以使用 Java 11+ HttpClientApache HttpClient 设置HTTP请求参数。无论是GET请求还是POST请求,都可以通过构建适当的请求对象来实现。希望这些示例能帮助你在开发中更好地设置HTTP请求参数。

相关推荐
爱学习的小可爱卢7 小时前
Java UDP编程实战:UDP数据报套接字编程DatagramPacket、DatagramSocket 、InetSocketAddress
java·udp·udp数据报
未来之窗软件服务7 小时前
幽冥大陆(三十五)S18酒店门锁SDK go语言——东方仙盟筑基期
java·前端·golang·智能门锁·仙盟创梦ide·东方仙盟·东方仙盟sdk
r***93487 小时前
【Redis】在Java中以及Spring环境下操作Redis
java·redis·spring
6***09268 小时前
如何快速搭建简单SpringBoot项目网页
java·spring boot·intellij-idea
q***44818 小时前
spring实例化对象的几种方式(使用XML配置文件)
xml·java·spring
q***98528 小时前
Spring Boot:Java开发的神奇加速器(二)
java·spring boot·后端
x***44018 小时前
Windows操作系统部署Tomcat详细讲解
java·windows·tomcat
小蒜学长8 小时前
基于spring boot的汽车4s店管理系统(代码+数据库+LW)
java·数据库·spring boot·后端·汽车
q***42058 小时前
Spring Data 什么是Spring Data 理解
java·后端·spring
一 乐8 小时前
餐厅管理智能点餐系统|基于java+ Springboot的餐厅管理系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·后端