2013-04-30 86 views
-1

因此,我正在編寫一個應用程序,將一個登錄請求發佈到我知道正在接收該帖子的url,該方法應該返回true,如果它進行身份驗證。這是我的方法到目前爲止,它每次都返回false,我做什麼想法都是錯誤的?爲什麼我的方法不認證?

public Boolean authenticate_user(String username, String password) { 
Boolean success = false; 
// Create a new HttpClient and Post Header 
HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("my url"); 
try { 
    // Add your data 
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
    nameValuePairs.add(new BasicNameValuePair("username", username)); 
    nameValuePairs.add(new BasicNameValuePair("password", password)); 
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

    // Execute HTTP Post Request 
    HttpResponse response = httpclient.execute(httppost); 
    // Response 
    HttpEntity entity = response.getEntity(); 
    if (entity != null) { 
     InputStream instream = entity.getContent(); 
     JSONTokener tokener = new JSONTokener(convertStreamToString(instream)); 
     JSONObject root = new JSONObject(tokener); 
     success = root.getBoolean("success"); 
     Integer id = root.getInt("id"); 
     String auth_token = root.getString("auth_token"); 
     String first_name = root.getString("first_name"); 

     //Save data to sharedprefs 
     SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); 
     editor.putString("hgtoken",auth_token); 
     editor.commit(); 
     } 
} catch (ClientProtocolException e) { 
} catch (IOException e) { 
} catch (JSONException e) { 
} 
if(success == true) { 
    return true; 
} else { 
    return false; 
} 
} 

也是我convertStreamToString方法如下

private static String convertStreamToString(InputStream is) { 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
    StringBuilder sb = new StringBuilder(); 

    String line = null; 
    try { 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "n"); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      is.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return sb.toString(); 
} 
+0

也是我回來的數據我我知道有沒有使用的變量,我只是真的擔心,確保我得到的數據回來,它正在反序列化,所以我的成功變量可以返回true – 2013-04-30 17:39:37

+0

我肯定會嘗試登錄例外情況,可能在你的代碼中有一處拋出。 – 2013-04-30 18:03:05

+0

並且您的convertStreamToString添加了「n」而不是「\ n」 – 2013-04-30 18:04:04

回答

0

的答案是我的代碼工作完全正常我愣神忘記行補充:

<uses-permission android:name="android.permission.INTERNET"></uses-permission> 

到我的Android清單.. 。感謝西蒙提醒我記錄我的例外這是什麼讓我關閉

相關問題