HTTP请求:java.io.IOException: Server returned HTTP response code: 405 for URL

4 篇文章 0 订阅

写Http请求的时候报405。

报错如下:
在这里插入图片描述

错误码405:表示不允许此方法:对于请求所标识的资源,不允许使用请求行中所指定的方法。

常用的几个方法:GET POST PUT DELETE

也就是说请求方法写错了。

看一下本地java代码中http的请求方法 和 第三方接口所允许的方法 是否一致,改成一致的就可以了。

我这里是GET请求,改成GET请求之后,依然报405这个错

继续找了找。

Http请求代码如下:

public static String doRequest2(String location , String requestMethod , String params ,String encoding,String token) throws Exception{
        URL url = new URL(location);
        HttpURLConnection connection =(HttpURLConnection) url.openConnection();
        connection.setRequestMethod(requestMethod); // 设置请求方式 GET、POST 等
//        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization", token);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setConnectTimeout(60000); // 设置连接超时时间,单位:ms 。
        connection.setReadTimeout(60000); // 设置读取超时时间,单位:ms 。
        connection.setDoInput(true); // 设置打开输入流 : default = true
        connection.setDoOutput(true); // 设置打开输出流:default = false
        connection.setUseCaches(false); // 设置是否启用用户缓存: default = false
        OutputStream outputStream = connection.getOutputStream(); // 获取输出流对象,准备往服务器写数据
        outputStream.write(params.getBytes());
        outputStream.flush();
        outputStream.close();

        // 获取服务器返回的响应状态
//        if(connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
//            System.out.println(" request fail code is" + HttpURLConnection.HTTP_OK);
//            return connection.getResponseMessage();
//        }

        // 读取服务器返回的数据
        BufferedReader reader = new BufferedReader(new
                InputStreamReader(connection.getInputStream(), encoding));
        String line ;
        StringBuffer sb = new StringBuffer();
        while((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
        String result = sb.toString();
        return result ;
    }

里面有几行代码:

在这里插入图片描述

问题就在这里了,方法改对了还报405,是因为调用了conn.getOutputStream()

这使 URLConnection 认为默认发送的是 POST,而不是所期望的 GET

我这里没有使用 OutputStream ,所以不需要打开它,不需要刷新它,然后也不需要close关闭它。

把它注掉就好了。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值