不知道是不是有人碰到过,用 HttpURLConnection 类提交 GET 请求,获取不到响应状态码
URL url = new URL(URL_ADDR);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_ACCEPTED) {
...
}
...
debug 的时候发现其实已经收到回复,但不知为何 header 没有 HTTP/1.1 这行,第一行是 Date ,导致 conn.getResponseCode()一直返回-1
不得已把
if (conn.getResponseCode() == HttpURLConnection.HTTP_ACCEPTED)
改成
if (conn.getResponseCode() == HttpURLConnection.HTTP_ACCEPTED) || conn.getHeaderField(0) != null)
发现运行结果是正确的(也就是说仅仅是没获取到正确的响应状态码)
编译工具为 Android Studio 1.3.2 , API 22/23 , AVD 与真机调试均失败
有谁知道是什么问题么
PS : URL_ADDR 是地址,我用 curl 试过,能获取到正常的 http 头,换成其他地址也是一样的结果