[英]Android: Checking HTTP response code: getting 200; should be 302
I am checking a website for 302 messages, but I keep receiving 200 in my code:我正在检查网站上的 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.
}
}
That is my Async task for checking.那是我用于检查的异步任务。 Here is the code implementing it:
这是实现它的代码:
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);
That log always returns 200, but I know that URL is 302 (it redirects to a search page on reddit.com).该日志总是返回 200,但我知道 URL 是 302(它重定向到 reddit.com 上的搜索页面)。 What am I doing wrong?
我做错了什么?
这一行只需要设置为 false:
HttpURLConnection.setFollowRedirects(false);
You can use HttpURLConnection .您可以使用HttpURLConnection 。 I have used it for response code in a few applications.
我在一些应用程序中将它用于响应代码。 I did not encounter any problems.
我没有遇到任何问题。
URL url = new URL("http://yoururl.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.