2
我得到IOException當我嘗試調用getCodeResponse()。當參數有效時,沒有異常,代碼響應是200.如果參數錯誤,服務器應該返回401代碼。我已經測試了hurl.it上的查詢,並且在出現錯誤參數的情況下,我獲得了401個代碼。也許HttpURLConnection類在發生錯誤代碼時拋出異常。HttpUrlConnection getResponseCode拋出IOException
URL url = new URL(sUrl);
String charset = "UTF-8";
conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(DEFAULT_TIMEOUT /* milliseconds */);
conn.setConnectTimeout(DEFAULT_TIMEOUT /* milliseconds */);
conn.setRequestMethod(methodType);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.addRequestProperty("Accept-Charset", charset);
conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.addRequestProperty(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os));
writer.write(query);
writer.flush();
writer.close();
//os.write(query.getBytes());
os.flush();
os.close();
conn.connect();
if(conn != null){
responseCode = conn.getResponseCode();
result = readResponse(conn);
}