我正在尝试将数据插入远程mysql数据库。我遇到的问题是位于远程服务器中时解析php文件。我总是得到类型java.lang.String的值php无法转换为JSONObject'错误。
这是我的php代码:
<?php
$response = array();
include 'db/connect.php';
include 'function.php';
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
if(isset($input['user_ID']) && isset($input['submit_your_activity']) && isset($input['how_was_the_activity'])){
$user_ID = $input['user_ID'];
$submit_your_activity = $input['submit_your_activity'];
$how_was_the_activity = $input['how_was_the_activity'];
if(!userExists($user_ID)){
$insertQuery = "INSERT INTO userdata(user_ID, submit_your_activity, how_was_the_activity) VALUES (?,?,?)";
if($stmt = $conn->prepare($insertQuery)){
$stmt->bind_param("sss",$user_ID,$submit_your_activity,$how_was_the_activity);
$stmt->execute();
$response["status"] = 0;
$response["message"] = "Successful";
$stmt->close();
} else {
$response["status"] = 1;
$response["message"] = "Failed";
}
}
}
else{
$response["status"] = 2;
$response["message"] = "Missing mandatory parameters";
}
echo json_encode($response);
?>
这是我的Java代码,用于连接到远程服务器中的php代码。我已经使用GET方法连接到AWS S3。
private void InsertData(){
JSONObject request = new JSONObject();
try{
request.put(KEY_USER_ID, user_ID);
request.put(KEY_SUBMIT_YOUR_ACTIVITY, submit_your_activity);
request.put(KEY_HOW_WAS_YOUR_ACTIVITY, how_was_the_activity);
}catch (JSONException e){
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, link, request, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
if (response.getInt(KEY_STATUS) == 0) {
Toast.makeText(getApplicationContext(), "success", Toast.LENGTH_LONG).show();
} else if (response.getInt(KEY_STATUS) == 1) {
editText1.setError("User Already Exists");
editText1.requestFocus();
} else{
Toast.makeText(getApplicationContext(), response.getString(KEY_MESSAGE), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
}
在Response.ErrorListener中引发错误消息。