【发布时间】:2026-02-01 11:10:01
【问题描述】:
我正在检查网站是否有 302 条消息,但我的代码中不断收到 200 条消息:
private class Checker extends AsyncTask<Integer,Void,Integer>{
protected void onPreExecute(){
super.onPreExecute();
//display progressdialog.
}
protected Integer doInBackground(Integer ...code){
try {
URL u = new URL ( "http://www.reddit.com/r/notarealurlinredditqwerty");
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("POST");
HttpURLConnection.setFollowRedirects(true);
huc.connect();
code[0] = huc.getResponseCode();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return code[0];
}
protected void onPostExecute(Integer result){
super.onPostExecute(result);
//dismiss progressdialog.
}
}
这是我的异步检查任务。这是实现它的代码:
int code = -1;
Checker checker = new Checker();
try {
code = checker.execute(code).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.d("code:", "" + code);
该日志总是返回 200,但我知道 URL 是 302(它重定向到 reddit.com 上的搜索页面)。 我做错了什么?
【问题讨论】:
-
不是 302 而是 404 - 页面不存在!但随后 reddit 会将您重定向到有效的“404”页面,这就是我猜你得到 200 的原因。
-
@alfasin 实际上是 302,因为它会自动重定向到搜索页面。不过,为什么这给了我 200(OK)?这绝对不应该发生。
-
您正在关注重定向 - 所以您的代码将获得 302,关注它,然后返回不发送重定向的第一页的状态代码。
-
@Raghunandan 啊,谢谢。那好多了。现在,只需要弄清楚为什么它仍然得到 200 的代码。