You need to enable JavaScript to run this app. 如何在Java中发送x-www-form-urlencoded格式POST请求并解决API密钥报错
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中发送x-www-form-urlencoded格式POST请求并解决API密钥报错

问题排查及修复方案

你代码里存在3个直接导致接口无法正确接收api_key的问题,按优先级修复即可:

  • 缺失必填请求头:POST提交表单格式参数时,必须显式添加Content-Type: application/x-www-form-urlencoded请求头,服务端会通过该头识别参数格式,未设置的话会无法解析你提交的api_key字段,直接判定密钥无效。
  • connect()调用时机错误:HttpURLConnection的connect()方法用于正式建立TCP连接,所有请求头配置、请求体写入操作都必须在调用connect()之前完成,你提前执行了连接逻辑,后续写入的api_key参数根本没有被发送到服务端。
  • 资源未正确关闭:输出流、输入流、连接使用后未关闭,虽不是本次报错的直接诱因,但会引发资源泄漏问题,建议同步修复。

修正后代码

String urlString = "https://example.com/";
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
// 新增Content-Type请求头
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
String data = URLEncoder.encode("api_key", "UTF-8")
        + "=" + URLEncoder.encode("xxxxx", "UTF-8");

// 先写请求体,getOutputStream会自动触发连接,不需要显式调用connect
try(OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream(), StandardCharsets.UTF_8)) {
    wr.write(data);
    wr.flush();
}

try (InputStream stream = urlConnection.getInputStream();
     BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8), 8)) {
    String result = reader.readLine();
    System.out.println(result);
} catch (IOException e){
    throw new RuntimeException("An error occured:\n" + e);
} finally {
    urlConnection.disconnect();
}

补充排查方向

如果修改后依然报错,可抓包确认实际发出的请求内容:核对api_key是否正确携带,部分接口要求密钥放在请求头而非请求体中,可同步核对接口文档的参数传递规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 16:57:02