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

Java使用HttpURLConnection执行GET返回204空响应curl正常如何解决

Java GET请求返回204无内容与curl结果不一致问题解决方案

问题根因

  • GET请求错误添加了仅POST表单需要的Content-Type: application/x-www-form-urlencoded请求头,导致服务端解析请求异常,返回204无内容
  • 未开启HttpURLConnection的自动重定向支持,和curl的--location参数行为不一致,请求没有跳转到实际返回错误信息的接口地址
  • 原有代码仅处理了200/204状态码的响应读取,非2xx状态码的错误响应内容存储在ErrorStream而非InputStream中,没有读取所以拿不到curl返回的错误提示

修正后代码

private String getDocId(Long invoiceNumber) {
    String get_url_qry = StringUtils.replace(GET_URL_QRY, ":1", Long.toString(invoiceNumber));
    get_url_qry = URLEncoder.encode(get_url_qry, StandardCharsets.UTF_8);
    final String get_url = GET_URL + get_url_qry;
    // 可打印最终请求URL和curl的请求地址对比,确认编码一致
    logger.info("GET请求地址:{}", get_url);
    try {
        URL url = new URL(get_url);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty("Authorization", GET_AUTH_ENC);
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", USER_AGENT);
        // 开启自动跟随重定向,匹配curl的--location参数行为
        con.setInstanceFollowRedirects(true);

        int responseCode = con.getResponseCode();
        logger.info("GET响应码:{}", responseCode);

        // 兼容读取正常响应和错误响应的内容
        InputStream inputStream;
        if (responseCode >= 200 && responseCode < 300) {
            inputStream = con.getInputStream();
        } else {
            inputStream = con.getErrorStream();
        }

        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        String resp = response.toString();
        logger.info("响应内容:{}", resp);

        // 自行解析响应内容返回docId即可
        return null;
    } catch (MalformedURLException e) {
        logger.error("创建URL异常:{},异常信息:{}", get_url, e.getMessage());
    } catch (IOException e) {
        logger.error("创建连接异常:{},异常信息:{}", get_url, e.getMessage());
    }
    return null;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 17:36:02