Android:检查HTTP响应代码:获得200;应该是302

时间:2013-09-26 05:03:56

标签: java android http

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

2 个答案:

答案 0 :(得分:0)

这一行只需要设置为false:

HttpURLConnection.setFollowRedirects(false);

答案 1 :(得分:0)

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

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