2013-09-26 124 views
0

我检查302个消息的网站,但我一直在我的代码接收200:Android:检查HTTP响应代码:获得200;应该是302

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)。 我在做什么错?

+0

http://android-spirit.blogspot.in/2013/08/cosume-phppost-method-webservice-in.html看这个 – Nirmal

+0

它不是302它404 - 页面不存在!但然后reddit重定向到一个有效的“404”页面,这就是为什么你会得到200我猜。 – alfasin

+0

@alfasin实际上,它是302,因为它会自动重定向到搜索页面。但是,为什么这给了我200(OK)?那肯定不会发生。 –

回答

0

此行只需要设置为false:

HttpURLConnection.setFollowRedirects(false); 
+0

仍然得到200.(在huc.setRequestMethod(“POST”);上面加上) –

+0

你的意思是在你再次将它设置为'true'之前? –

+0

@AlexMDC哦,我应该澄清:我删除了它下面的那一行。它只会将它设置为假 - 仍然会达到200。 –