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