当我尝试调用getCodeResponse()时,我得到了IOException。当参数有效时,没有异常,代码响应为200.如果参数错误,服务器应返回401代码。我在hurl.it上测试了查询,如果参数错误,我得到了401代码。可能HttpURLConnection类在发生错误代码时抛出异常。
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);
}
答案 0 :(得分:1)
IOException意味着有401响应。打印堆栈跟踪,如果其他一切都正确,它将给出401响应。类似于:java.io.IOException: Server returned HTTP response code: 401 for URL: