设置connection.setRequestMenthod(“GET”)不生效

 

背景介绍:想要访问开放的获取天气信息的接口,该接口的请求方式是GET类型的,故代码中做了如下设置:

public HttpURLConnection getConnection(String url){
        HttpURLConnection connection = null;
        try {
            // 打开和URL之间的连接
            URL postUrl = new URL(url);
            connection = (HttpURLConnection) postUrl.openConnection();
            // 设置通用的请求属性
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Charset", "utf-8");
            connection.setRequestProperty("Accept-Charset", "utf-8");
			DataOutputStream out = null;
            // 建立实际的连接
            connection.connect();
            out = new DataOutputStream(connection.getOutputStream());
            out.flush();
            out.close();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            while ((line = reader.readLine()) != null) {
                httpResults = httpResults + line.toString();
            }
            reader.close();
            // 断开连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

但是,在运行测试用例的时候,报java.io.IOException: Server returned HTTP response code: 405 for URL: http://www.weather.com.cn/data/cityinfo/101280601.html

http接口状态405表示:(方法禁用) 禁用请求中指定的方法。于是猜想我代码中是虽设置了请求方式为:get,但是否这一设置成功生效了呢?于是通过debug模式调式代码,发现后台正真的处理方式其实还是post。那么,系统报405的错误就显得很正常了。

那么为何,我设置了connection.setRequestMethod("GET");却未生效呢?通过仔细读代码,发现这段代码并没有实际的用处,于是尝试将其注释了,然后再运行我的测试用例,发现成功的返回接口数据。

out = new DataOutputStream(connection.getOutputStream());

out.flush();

out.close();

 

通过一波百度,原来DataOutputStream out = new DataOutputStream(connection.getOutputStream());

执行这句会自动把接口的请求类型设置为POST, 因为只有POST方法才能发送 “附加数据” 也就是你要发送的JSON字符串。

GET方法不能发送“附加数据”,所有的数据必须方法请求地址的URL中(不理解这句话,可以了解一下get请求和post请求的区别)。

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值