在android4.0中http get请求自动变成post请求

昨天发现一个奇怪的现象,我一个普通的HTTP GET请求下载apk文件,服务器却总是返回405 Method Not Allowed。百思不得其解。
今天我用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 );
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值