Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/224.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android:检查HTTP响应代码:获取200;应该是302_Java_Android_Http - Fatal编程技术网

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

Java Android:检查HTTP响应代码:获取200;应该是302,java,android,http,Java,Android,Http,我正在检查一个网站的302条消息,但我的代码中不断收到200条: private class Checker extends AsyncTask<Integer,Void,Integer>{ protected void onPreExecute(){ super.onPreExecute(); //display progressdialog. } protected Integer doInBackground(Integ

我正在检查一个网站的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.
    }
}
那个日志总是返回200,但我知道URL是302(它重定向到reddit.com上的搜索页面)。
我做错了什么?

这行只需要设置为false:

HttpURLConnection.setFollowRedirects(false);
你可以用。我在一些应用程序中使用它作为响应代码。我没有遇到任何问题

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

注意这不是302而是404-页面不存在!但reddit会将您重定向到一个有效的“404”页面,这就是为什么我猜您会得到200。@实际上,它是302,因为它会自动重定向到搜索页面。不过,为什么这给了我200(好)?这绝对不应该发生。您正在执行重定向-因此您的代码将获得302,然后返回未发送重定向的第一页的状态代码。@Raghunandan啊,谢谢。那好多了。现在,我要弄清楚为什么代码仍然是200,仍然是200。(添加在huc.setRequestMethod(“POST”);@AlexMDC哦,我应该澄清一下:我删除了它下面的那一行。它只将其设置为false——仍然得到200。
URL url = new URL("http://yoururl.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();