【发布时间】:2014-07-31 12:07:34
【问题描述】:
我是 Android Volley 库的新手。我将用户名和密码发送到 API,API 返回用户详细信息。所以这是我在 android 中的 LoginUser 方法。
public void LoginUser(){
// Tag used to cancel the request
String tag_json_obj = "json_obj_req";
String url = "http://example.com/myfile/mobile_api/";
//final ProgressDialog pDialog = ProgressDialog.show(getParent(), "Please wait", "Login user");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
if(response.getString(KEY_SUCCESS)!=null){
String res = response.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
JSONObject json_user = response.getJSONObject("user");
Toast.makeText(getApplicationContext(), "User Logged in.. " + json_user.getString("name"), Toast.LENGTH_LONG).show();
}
}
else if(response.getString(KEY_ERROR)!=null){
String res = response.getString(KEY_ERROR);
if(Integer.parseInt(res) == 1){
Toast.makeText(getApplicationContext(), response.getString("error_msg"), Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//pDialog.hide();
}
Log.d(TAG, response.toString());
//pDialog.hide();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Log.d(TAG, "Error: " + error.getMessage());
//pDialog.hide();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("tag", login_tag);
params.put("email", Email);
params.put("password", Pass);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
这是我的 API index.php 文件
if ($tag == 'login') {
$email = $_POST['email'];
$password = $_POST['password'];
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
$response["success"] = 1;
$response["uid"] = $user["id"];
$response["user"]["name"] = $user["name"];
$response["user"]["phone"] = $user["contact_no"];
$response["user"]["email"] = $user["email"];
$response["user"]["reg_date"] = $user["reg_date"];
echo json_encode($response);
} else {
$response["error"] = 1;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
但我收到来自 Json 的以下错误
07-31 16:58:27.307: E/JSON Parser(7506): 解析数据时出错 org.json.JSONException: 类型 java.lang.String 的值不能转换为 JSONObject
那么这是使用 Volley 连接移动 API 和 Android 应用程序的正确方法吗?或者谁能解释我这样做的原因?
【问题讨论】:
-
也发布您的 json 响应。
-
其实我没有得到任何回应。这就是问题所在。我收到了上述错误消息。错误:org.json.JSONException:java.lang.String 类型的值访问无法转换为 JSON
-
好吧,我想我找到了问题所在。我收到该错误消息是因为如果标签不正确,它会返回一个字符串“拒绝访问”,它会给出“拒绝访问”消息。
标签: android json api android-volley jsonobject