背景介绍:想要访问开放的获取天气信息的接口,该接口的请求方式是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请求的区别)。