愉快的开始
一段出现bug的代码如下:
HttpsURLConnection conn = (HttpsURLConnection)new java.net.URL("serverUrl").openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.connect();
在使用HttpURLConnection时,我们可以指定setRequestMethod(String method)来指定请求方式。我们也可以从注释中看到所有支持的选项,默认是 GET。
/**
* Sets the request command which will be sent to the remote HTTP server.
* This method can only be called before the connection is made.
*
* @param method
* the string representing the method to be used.
* @throws ProtocolException
* if this is called after connected, or the method is not
* supported by this HTTP implementation.
* @see #getRequestMethod()
* @see #method
*/
public void setRequestMethod(String method) throws ProtocolException {
看上去非常美好。
于是乎,这段代码在经过5分钟的考虑后,麻溜的上线了。
服务端同学上线
接到服务端同学反馈,说有大量的POST请求正在请求服务器。(GET请求由于做了转发,最终请求到CDN上,对服务器压力很小)。一抓日志,全部机器为Android。 而请求的接口只有上述一个地方。
Review一遍代码呀!
再看了一遍,没毛病呀,指定Method=GET。正符合文档对这个方法的解释。可证据表明,这段代码确实有问题。接着使用MAC下抓包神器Charles .一抓包确实,发出的是POST请求!!
源码是最忠实的朋友
在翻阅了官方说明,发现以下解释:
可以看到在使用了setDoOutput(true)后,会将method指定为POST;这点在源码中也得到了体现。