You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jersey查询参数传递问题:含空格字符串报错及多方案求解

解决Jersey API传递含空格查询参数的问题

问题原因

URL不允许直接包含空格等特殊字符,直接拼接带空格的字符串会导致URL格式非法,触发异常。核心解决思路是对查询参数进行URL编码(将空格转为%20或+),而Jersey服务端会自动完成解码,无需修改API代码。

解决方案

方案1:使用URLEncoder手动编码查询参数

Java标准库的URLEncoder可将字符串转为符合URL规范的格式,需指定UTF-8字符集保证编码正确性。

修改主类代码:

public class MainClass {
    public static void main(String[] args) throws IOException {
        System.out.println("enter : ");
        Scanner sc = new Scanner(System.in);
        String query = sc.nextLine();
        // 对查询参数进行URL编码
        String encodedQuery = URLEncoder.encode(query, "UTF-8");
        URL obj = new URL("http://localhost:8080/Sample/api/newstring/next?query=" + encodedQuery);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-Type", "text/plain"); // 修正原代码中Content-Type的拼写错误
        BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        System.out.println(reader.readLine());
    }
}

方案2:使用java.net.URI构建安全URL

URI类会自动处理URL各组件的编码,避免手动编码遗漏(如多参数场景),是更健壮的实现方式。

修改主类代码:

public class MainClass {
    public static void main(String[] args) throws IOException, URISyntaxException {
        System.out.println("enter : ");
        Scanner sc = new Scanner(System.in);
        String query = sc.nextLine();
        
        // 分组件构建URI,自动完成参数编码
        URI uri = new URI(
            "http",
            null,
            "localhost",
            8080,
            "/Sample/api/newstring/next",
            "query=" + query,
            null
        );
        URL obj = uri.toURL();
        
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-Type", "text/plain");
        BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        System.out.println(reader.readLine());
    }
}

方案3:使用Apache HttpClient(第三方库)

若项目需处理复杂HTTP请求,Apache HttpClient可自动处理参数编码,简化代码逻辑。

先添加Maven依赖:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.14</version> <!-- 使用最新稳定版 -->
</dependency>

主类代码示例:

import org.apache.http.client.methods.CloseableHttpResponse;
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 org.apache.http.util.EntityUtils;

public class MainClass {
    public static void main(String[] args) throws Exception {
        System.out.println("enter : ");
        Scanner sc = new Scanner(System.in);
        String query = sc.nextLine();
        
        // 用URIBuilder构建请求,自动编码参数
        URIBuilder builder = new URIBuilder("http://localhost:8080/Sample/api/newstring/next");
        builder.addParameter("query", query);
        HttpGet request = new HttpGet(builder.build());
        
        try (CloseableHttpClient client = HttpClients.createDefault();
             CloseableHttpResponse response = client.execute(request)) {
            String result = EntityUtils.toString(response.getEntity());
            System.out.println(result);
        }
    }
}

最优方案选择

推荐使用方案2(java.net.URI),理由:

  1. 属于Java标准库,无需引入第三方依赖;
  2. 自动处理所有URL组件的编码,避免手动编码的遗漏或错误;
  3. 代码结构清晰,可读性与可维护性更强。

若项目已使用Apache HttpClient,方案3也是高效选择,它提供了更丰富的HTTP功能支持。

服务端代码说明

你的API代码无需修改,Jersey的@QueryParam注解会自动对编码后的参数进行解码,返回原始带空格的字符串。

内容的提问来源于stack exchange,提问作者Alex jeffrin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 15:39:37