【问题标题】:Android: Checking HTTP response code: getting 200; should be 302Android:检查 HTTP 响应代码:得到 200;应该是 302
【发布时间】: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 的代码。

标签: java android http


【解决方案1】:

这一行只需要设置为false即可:

HttpURLConnection.setFollowRedirects(false);

【讨论】:

  • 仍然是 200。(添加到 huc.setRequestMethod("POST");) 的正上方
  • @AlexMDC 哦,我应该澄清一下:我删除了它下面的那一行。它只是将其设置为 false - 仍为 200。
【解决方案2】:

您可以使用HttpURLConnection。我已经将它用于一些应用程序中的响应代码。我没有遇到任何问题。

URL url = new URL("http://yoururl.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();

【讨论】: