为什么我的方法不会被认证?

时间:2013-04-30 17:28:41

标签: java android authentication

所以我正在编写一个应用程序,将登录请求发布到我知道正在接收帖子的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();
}

1 个答案:

答案 0 :(得分:0)

答案是我的代码完全正常我愚蠢地忘了添加行:

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

到我的Android清单...感谢Simon提醒我记录我的异常,这是什么让我失望