我一直在尝试遵循本教程:http ://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/ 。它是创建一个android登录应用程序。我已经阅读了评论,它没有明确回答发生此错误 500 服务器错误的原因以及如何解决它。
我进行了研究,一个站点建议将其放入getJsonFromURL method
AsyncTask 中,因为它似乎在主线程上运行。但是,这与服务器错误没有区别。
当下面的代码运行时,Logcat 读出内部服务器错误 500。这意味着服务器无法理解发送给它的内容。我在 JSONParser.java 中注释掉了这一行:
httpPost.setEntity(new UrlEncodedFormEntity(params));
并且该 url 与服务器一起使用并获得 200 ok 服务器响应。
我只能假设处理名称值对的方式是错误的。但是,我发现用于List<NameValuePair>
收集登录值的每个示例都与下面的代码具有相同的实现。
您能否查看下面的代码或向我建议另一种获取名称值对以通过 POST 方法发送到服务器的方法?
// JSONParser.java
package library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
Log.v("name value pairs ",params.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
Log.v("Http Response",httpResponse.getStatusLine().toString());
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
注册活动.java:
package com.example.androidhive;
import org.json.JSONException;
import org.json.JSONObject;
import library.DatabaseHandler;
import library.UserFunctions;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RegisterActivity extends Activity {
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
inputEmail = (EditText) findViewById(R.id.registerEmail);
inputPassword = (EditText) findViewById(R.id.registerPassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
// Close Registration View
finish();
}
});
}
}
用户函数.java:
package library;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.util.Log;
import android.content.Context;
public class UserFunctions {
private JSONParser jsonParser;
// Testing in Leobee.com
// use http://10.0.2.2/ to connect to your localhost ie http://localhost/
private static String loginURL = "http://www.leobee.com/android/push/login/";
private static String registerURL = "http://www.leobee.com/android/push/login/index.php?";
private static String login_tag = "login";
private static String register_tag = "register";
// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
/**
* function make Login Request
* @param email
* @param password
* */
public JSONObject loginUser(String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
// return json
// Log.e("JSON", json.toString());
return json;
}
/**
* function make Login Request
* @param name
* @param email
* @param password
* */
public JSONObject registerUser(String name, String email, String password){
Log.v("register user", name+ " "+email +" " + password);
// Building Parameters
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
// getting JSON Object
Log.v("url placed in json object", registerURL);
// Log.v("url placed in json object", params);
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
// return json
Log.v("JSON parser string", json.toString());
return json;
}
/**
* Function get Login status
* */
public boolean isUserLoggedIn(Context context){
DatabaseHandler db = new DatabaseHandler(context);
int count = db.getRowCount();
if(count > 0){
// user logged in
return true;
}
return false;
}
/**
* Function to logout user
* Reset Database
* */
public boolean logoutUser(Context context){
DatabaseHandler db = new DatabaseHandler(context);
db.resetTables();
return true;
}
}
使用名称值对记录 cat 500 错误:
05-27 05:47:07.342: V/register user(409): Name email@email.com pass
05-27 05:47:07.353: V/url placed in json object(409): http://www.leobee.com/android/push/login/index.php?
05-27 05:47:07.362: V/name value pairs(409): [tag=register, name=Name, email=email@email.com, password=pass]
05-27 05:47:08.493: V/Http Response(409): HTTP/1.1 500 Internal Server Error
05-27 05:47:08.803: E/JSON Parser(409): Error parsing data org.json.JSONException: End of input at character 0 of
05-27 05:47:08.803: D/AndroidRuntime(409): Shutting down VM
05-27 05:47:08.803: W/dalvikvm(409): threadid=1: thread exiting with uncaught exception (group=0x40015560)
05-27 05:47:08.824: E/AndroidRuntime(409): FATAL EXCEPTION: main
05-27 05:47:08.824: E/AndroidRuntime(409): java.lang.NullPointerException
05-27 05:47:08.824: E/AndroidRuntime(409): at library.UserFunctions.registerUser(UserFunctions.java:68)
05-27 05:47:08.824: E/AndroidRuntime(409): at com.example.androidhive.RegisterActivity$1.onClick(RegisterActivity.java:55)
05-27 05:47:08.824: E/AndroidRuntime(409): at android.view.View.performClick(View.java:2485)
05-27 05:47:08.824: E/AndroidRuntime(409): at android.view.View$PerformClick.run(View.java:9080)
05-27 05:47:08.824: E/AndroidRuntime(409): at android.os.Handler.handleCallback(Handler.java:587)
05-27 05:47:08.824: E/AndroidRuntime(409): at android.os.Handler.dispatchMessage(Handler.java:92)
05-27 05:47:08.824: E/AndroidRuntime(409): at android.os.Looper.loop(Looper.java:130)
05-27 05:47:08.824: E/AndroidRuntime(409): at android.app.ActivityThread.main(ActivityThread.java:3683)
05-27 05:47:08.824: E/AndroidRuntime(409): at java.lang.reflect.Method.invokeNative(Native Method)
05-27 05:47:08.824: E/AndroidRuntime(409): at java.lang.reflect.Method.invoke(Method.java:507)
05-27 05:47:08.824: E/AndroidRuntime(409): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-27 05:47:08.824: E/AndroidRuntime(409): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-27 05:47:08.824: E/AndroidRuntime(409): at dalvik.system.NativeStart.main(Native Method)
Logcat 200 ok,没有名称值对:
05-27 05:51:39.863: D/dalvikvm(444): GC_EXTERNAL_ALLOC freed 70K, 49% free 2778K/5379K, external 2032K/2137K, paused 40ms
05-27 05:51:46.415: W/KeyCharacterMap(444): No keyboard for id 0
05-27 05:51:46.415: W/KeyCharacterMap(444): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
05-27 05:52:06.862: V/register user(444): no value@pairs.com url
05-27 05:52:06.862: V/url placed in json object(444): http://www.leobee.com/android/push/login/index.php?
05-27 05:52:06.883: V/name value pairs(444): [tag=register, name=no, email=value@pairs.com, password=url]
05-27 05:52:07.893: V/Http Response(444): HTTP/1.1 200 OK
05-27 05:52:07.902: E/JSON(444): Access Deniedn
05-27 05:52:07.912: E/JSON Parser(444): Error parsing data org.json.JSONException: Value Access of type java.lang.String cannot be converted to JSONObject
05-27 05:52:07.912: D/AndroidRuntime(444): Shutting down VM
05-27 05:52:07.912: W/dalvikvm(444): threadid=1: thread exiting with uncaught exception (group=0x40015560)
05-27 05:52:07.923: E/AndroidRuntime(444): FATAL EXCEPTION: main
05-27 05:52:07.923: E/AndroidRuntime(444): java.lang.NullPointerException
05-27 05:52:07.923: E/AndroidRuntime(444): at library.UserFunctions.registerUser(UserFunctions.java:68)
05-27 05:52:07.923: E/AndroidRuntime(444): at com.example.androidhive.RegisterActivity$1.onClick(RegisterActivity.java:55)
05-27 05:52:07.923: E/AndroidRuntime(444): at android.view.View.performClick(View.java:2485)
05-27 05:52:07.923: E/AndroidRuntime(444): at android.view.View$PerformClick.run(View.java:9080)
05-27 05:52:07.923: E/AndroidRuntime(444): at android.os.Handler.handleCallback(Handler.java:587)
05-27 05:52:07.923: E/AndroidRuntime(444): at android.os.Handler.dispatchMessage(Handler.java:92)
05-27 05:52:07.923: E/AndroidRuntime(444): at android.os.Looper.loop(Looper.java:130)
05-27 05:52:07.923: E/AndroidRuntime(444): at android.app.ActivityThread.main(ActivityThread.java:3683)
05-27 05:52:07.923: E/AndroidRuntime(444): at java.lang.reflect.Method.invokeNative(Native Method)
05-27 05:52:07.923: E/AndroidRuntime(444): at java.lang.reflect.Method.invoke(Method.java:507)
05-27 05:52:07.923: E/AndroidRuntime(444): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-27 05:52:07.923: E/AndroidRuntime(444): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-27 05:52:07.923: E/AndroidRuntime(444): at dalvik.system.NativeStart.main(Native Method)