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

Java使用HttpURLConnection请求服务器返回405错误求助

解决HttpURLConnection请求返回405错误的问题

HTTP 405错误表示服务器不接受当前使用的请求方法。你的代码里虽然设置了setRequestMethod("GET"),但调用connection.getOutputStream()会强制HttpURLConnection把请求方法改为POST——因为该类默认认为只要向输出流写数据,就是POST请求。而你访问的服务器接口只支持GET方法,所以返回405。浏览器直接访问是标准的GET请求(参数拼在URL中),所以能正常响应。

解决方案

  • 改用标准GET请求,参数拼入URL
    把请求参数直接拼接在URL的查询字符串部分,不要使用输出流发送参数,代码修改如下:

    // 先构造带参数的URL
    Map<String, String> params = new HashMap<>();
    params.put("param1", "value1");
    String fullUrl = URL_STRING + "?" + ParameterStringBuilder.getParamsString(params);
    
    URL url = new URL(fullUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    
    // 无需setDoOutput(true)和输出流相关代码
    
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    StringBuffer content = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        content.append(inputLine);
    }
    
    connection.disconnect();
    System.out.println(content);
    

    注意:确保ParameterStringBuilder.getParamsString方法能正确对参数做URL编码,避免特殊字符导致的参数解析失败。

  • 如果服务器支持POST,可切换为POST请求
    若服务器接口同时支持POST方法,也可以将请求方法改为POST,保留输出流代码:

    URL url = new URL(URL_STRING);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    // 把GET改成POST
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
    
    Map<String, String> params = new HashMap<>();
    params.put("param1", "value1");
    out.writeBytes(ParameterStringBuilder.getParamsString(params));
    out.flush();
    out.close();
    
    // 后续读取响应的代码不变
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    StringBuffer content = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        content.append(inputLine);
    }
    
    connection.disconnect();
    System.out.println(content);
    

    但根据你描述的情况,浏览器用GET能正常访问,说明服务器只支持GET,所以第一种方案更适用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 05:07:16