0

我正在检查一个网站是否有 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 上的搜索页面)。我究竟做错了什么?

4

2 回答 2

0

只需将此行设置为 false:

HttpURLConnection.setFollowRedirects(false);
于 2013-09-26T05:38:18.783 回答
0

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

URL url = new URL("http://yoururl.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
于 2021-01-07T21:20:42.027 回答