2013-09-26 120 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。 –