昨天发现一个奇怪的现象,我一个普通的HTTP GET请求下载apk文件,服务器却总是返回405 Method Not Allowed。百思不得其解。
今天我用wireshark抓取数据包发现,发出去的请求居然不是GET ,而是POST !!!
代码如下(部分):
最后,我发现,问题出现在这句上面
conn.setDoInput(true)默认是打开的,但是在android4.0中,如果你设置了conn.setDoOutput(true),那么请求方法会默认变成POST。
而在android4.0以前,请求方法在setRequestMethod中指定就不会变。
修改后的代码:
今天我用wireshark抓取数据包发现,发出去的请求居然不是GET ,而是POST !!!
代码如下(部分):
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
|
//MalformedURLException: a MalformedURLException may be thrown here
URL url =
new
URL(_url);
//a IOException may be thrown here eg:UnknownHostException
try
{
conn = (HttpURLConnection) url.openConnection();
}
catch
(IOException e) {
e.printStackTrace();
throw
e;
}
//a IOException may be thrown here eg:ProtocolException, but it's unusual
conn.setRequestMethod(request.getMethod());
//request是我封装的类,此例中request.getMethod() 返回GET
conn.setDoInput(
true
);
conn.setDoOutput(
true
);
|
最后,我发现,问题出现在这句上面
01
|
conn.setDoOutput(
true
);
|
conn.setDoInput(true)默认是打开的,但是在android4.0中,如果你设置了conn.setDoOutput(true),那么请求方法会默认变成POST。
而在android4.0以前,请求方法在setRequestMethod中指定就不会变。
修改后的代码:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
|
//MalformedURLException: a MalformedURLException may be thrown here
URL url =
new
URL(_url);
//a IOException may be thrown here eg:UnknownHostException
try
{
conn = (HttpURLConnection) url.openConnection();
}
catch
(IOException e) {
e.printStackTrace();
throw
e;
}
//a IOException may be thrown here eg:ProtocolException, but it's unusual
conn.setRequestMethod(request.getMethod());
if
(
"POST"
.equalsIgnoreCase(request.getMethod())) {
conn.setDoInput(
true
);
conn.setDoOutput(
true
);
}
|