奇葩事情年年有,今天特别多.以前就进过HttpURLConnection的坑,今天又进去了.
在早上编代码调试的时候,发现了这样一个问题,我用GET请求提交数据给服务器,服务器返回我405.明明是GET请求,在服务器端的日志上,却显示我POST请求,百思不得其解!
先解释下405,
·405 - 用来访问本页面的 HTTP 谓词不被允许(方法不被允许)
然后附上GET请求的代码:
乍一看没问题,但是问题出在HttpURLConnection httpURLConnection = null; try { URL urlGet = new URL(newURL); httpURLConnection = (HttpURLConnection) urlGet.openConnection(); // 配置HttpURLConnection httpURLConnection.setRequestMethod("GET"); //get方式请求 httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setConnectTimeout(TIMEOUT); httpURLConnection.setReadTimeout(TIMEOUT * 3); // 连接 httpURLConnection.connect(); Log.d("TAG","连接......."); String content = getStringFromInputStream(httpURLConnection.getInputStream()); int responseCode = httpURLConnection.getResponseCode(); Log.d("TAG","vcontent="+content); if (responseCode == HttpURLConnection.HTTP_OK) { Log.d("TAG","进行Get请求:success"); return content; } else { Log.d("TAG","进行Get请求:fail:"+responseCode); throw new RuntimeException("请求‘" + newURL +"’失败!"); } } catch (MalformedURLException e) { Log.d("TAG","进行Get请求:异常"); e.printStackTrace(); } catch (IOException e) { Log.d("TAG","进行Get请求:IO异常"); e.printStackTrace(); } finally { if(httpURLConnection != null) { httpURLConnection.disconnect(); httpURLConnection = null; } }
<span style="white-space:pre"> </span>httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true);
这两行上.
<span style="white-space:pre"> </span>当我去掉这两行的时候,服务器恢复了正常的请求方式,连接好了数据库!
<span style="white-space:pre"> </span>那么来看看这两行有什么作用?请先看这篇文章:http://blog.csdn.net/u010665691/article/details/45558119
<span style="white-space:pre"> </span>简单来说,<span style="color: rgb(51, 51, 51); font-family: Georgia, 'Bitstream Charter', serif; font-size: 16px; line-height: 24px;">get请求的话默认就行了,post请求需要setDoOutput(</span><span style="color: rgb(51, 51, 51); font-family: Georgia, 'Bitstream Charter', serif; font-size: 16px; line-height: 24px; border: 0px; margin: 0px; padding: 0px; vertical-align: baseline; background: transparent;">true</span><span style="color: rgb(51, 51, 51); font-family: Georgia, 'Bitstream Charter', serif; font-size: 16px; line-height: 24px;">),这个默认是false的,所以问题就奇怪在你设置了setDoOutput(true)的时候,不知为何的就被转换成POST请求提交到服务器上了,而当我删除这两行的时候,请求恢复正常!</span>
<span style="color: rgb(51, 51, 51); font-family: Georgia, 'Bitstream Charter', serif; font-size: 16px; line-height: 24px;"><span style="white-space:pre"> </span>奇葩问题,在此记录下!</span>