2012-03-31 129 views
0

我有一個登錄表單,當前正在使用HTTP Post Request登錄參數並登錄到網站。我不確定服務器類型,因此可能是問題所在。一旦獲得登錄憑證,它就會將輸入流轉換爲一個字符串(所有html)並將其設置爲textview。這裏的登錄:Android登錄網站 - 總是返回登錄頁面數據

private void postLoginData() throws ClientProtocolException, IOException { 
    // Create a new HttpClient and Post Header 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("loginurl"); // Changed for question. 

    try { 
     // Add your data 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
     nameValuePairs.add(new BasicNameValuePair("sid", "username")); 
     nameValuePairs.add(new BasicNameValuePair("pin", "pass")); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     // Execute HTTP Post Request 
     HttpResponse response = httpclient.execute(httppost); 
     String finalres = inputStreamToString(response.getEntity().getContent()).toString(); 
     tvStatus.setText(finalres); 

    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
    } 
} 

而這裏的inputStreamToString()

private StringBuilder inputStreamToString(InputStream is) throws IOException { 
    String line = ""; 
    StringBuilder total = new StringBuilder(); 

    // Wrap a BufferedReader around the InputStream 
    BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 

    // Read response until the end 
    while ((line = rd.readLine()) != null) { 
     total.append(line); 
    } 

    // Return full string 
    return total; 
} 

的問題是,它永遠只是返回登錄頁面的HTML。當用戶在網站上登錄失敗時,它會有一條消息來表明這一點。即使我添加不正確的憑據,它也不會顯示任何不同的內容。同樣,如果我添加正確的登錄名,它仍然顯示我只是登錄頁面的HTML。

+0

登錄後是否需要獲取頁面內容?如果它是200或401,請檢查HTTP狀態。如果只是想進行身份驗證,則不需要獲取數據。 – 2012-03-31 04:37:17

+0

您能否指出我在檢查HTTP狀態方面的正確方向?我一直在使用Google,並且找不到它。 – 2012-03-31 04:40:56

+0

寫入response.getStatusLine()。getStatusCode();到Logcat。 – yorkw 2012-03-31 04:50:10

回答

2

檢查HTTP狀態。做這樣的事情

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { 
    //Do Something here.. I'm logged in. 
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { 
    // Do Something here. Access Denied. 
} else { 
    // IF BOTH CASES not found e.g (unknown host and etc.) 
} 

這將完全符合你想要檢查的狀態。謝謝

+0

它總是返回第一個結果。 – 2012-03-31 04:59:20

+0

如果它出現在第一個條件中,那麼這意味着您已成功登錄。現在,它取決於您需要使用該身份驗證所做的事情。 – 2012-03-31 05:00:27

+0

問題是,即使我輸入了不正確的登錄名,也會發生相同的結果。 – 2012-03-31 05:05:45

1

我想這個問題類似於this question。檢查一下,有一些解決方案,這可能會爲你解決它。