Java 为什么我的方法无法验证?

Java 为什么我的方法无法验证?,java,android,authentication,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 httpcli

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

答案是我的代码运行得非常好,我愚蠢地忘记添加行:

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


感谢Simon提醒我记录我的异常,这是我的通风报信

而且我得到的数据是json数据,我知道有未使用的变量,因此我只担心确保我得到的数据是正确的反序列化,这样我的成功变量才能返回trueI您肯定会尝试记录异常,可能代码中的某个地方抛出了一个异常。您的convertStreamToString会添加一个“n”而不是“\n”,而且如果您自己将流转换为字符串,则不需要JSONTokener。然后可以直接构造JSONObject
<uses-permission android:name="android.permission.INTERNET"></uses-permission>