愉快的開始
一段出現(xiàn)bug的代碼如下:
HttpsURLConnection conn = (HttpsURLConnection)new java.net.URL("serverUrl").openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.connect();
在使用HttpURLConnection時(shí)谅畅,我們可以指定setRequestMethod(String method)來指定請(qǐng)求方式滑蚯。我們也可以從注釋中看到所有支持的選項(xiàng)应民,默認(rèn)是 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 {
看上去非常美好。
于是乎枷踏,這段代碼在經(jīng)過5分鐘的考慮后菩暗,麻溜的上線了。
服務(wù)端同學(xué)上線
接到服務(wù)端同學(xué)反饋旭蠕,說有大量的POST請(qǐng)求正在請(qǐng)求服務(wù)器停团。(GET請(qǐng)求由于做了轉(zhuǎn)發(fā),最終請(qǐng)求到CDN上掏熬,對(duì)服務(wù)器壓力很杏映怼)。一抓日志旗芬,全部機(jī)器為Android舌胶。 而請(qǐng)求的接口只有上述一個(gè)地方。
Review一遍代碼呀疮丛!
再看了一遍幔嫂,沒毛病呀,指定Method=GET这刷。正符合文檔對(duì)這個(gè)方法的解釋婉烟。可證據(jù)表明暇屋,這段代碼確實(shí)有問題似袁。接著使用MAC下抓包神器Charles .一抓包確實(shí),發(fā)出的是POST請(qǐng)求8琅佟昙衅!
源碼是最忠實(shí)的朋友
在翻閱了官方說明,發(fā)現(xiàn)以下解釋:
可以看到在使用了setDoOutput(true)后定鸟,會(huì)將method指定為POST;這點(diǎn)在源碼中也得到了體現(xiàn)而涉。