我正在尝试开发一个简单的Android应用程序,它将用户的信息存储到服务器上。因此,我开发了应用程序的前端,并在服务器上创建了MySql数据库。我已经编写了更新数据库所需的PHP脚本,并且已经在Android代码中编写了一个解析器以解析并将数据发送到服务器。
问题是,我无法将参数从Android代码发送到PHP代码。我已经在SO和其他许多论坛上阅读了很多问题和答案,但是似乎没有任何工作对我有用。请帮忙。
我创建了一个ASync Task,该任务执行将数据发送到服务器的任务。这是异步任务的代码。
class CreateNewUser extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
// Creating user
protected String doInBackground(String... args) {
String name = user.getName();
String firstname = user.getFirstName();
String lastname = user.getLastName();
String number = user.getNumber();
String email = user.getEmail();
String status = user.getStatus();
String dob = user.getDob();
// Building Parameters
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("firstname", firstname));
params.add(new BasicNameValuePair("number", number));
params.add(new BasicNameValuePair("lastname", lastname));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("status", status));
params.add(new BasicNameValuePair("dob", dob));
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
}
}
上面的代码中的“ url_create_product”是服务器的PHP创建用户文件的URL,稍后还将在其中提供该文件。
接下来是我的JSONParser文件。
package com.osahub.rachit.osachatting.server;
import android.util.Log;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
/**
* Created by Rachit on 13-06-2015.
*/
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
/*HttpParams httpParams = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);*/
HttpPost httpPost = new HttpPost(url);
UrlEncodedFormEntity urlEncoded = new UrlEncodedFormEntity(params, "UTF-8");
httpPost.setEntity(urlEncoded);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
is = entity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
is = httpResponse.getEntity().getContent();
}
} 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();
} 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.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
最后,我的create_user.php文件在下面。
create_user.php
<?php
$response = array();
// check for required fields
if (isset($_POST['number'])) {
$name = $_POST['name'];
$first_name = $_POST['first_name'];
$number = $_POST['number'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$status = $_POST['status'];
$dob = $_POST['dob'];
// include db connect class
require_once __DIR__ . '/user_info_connect.php';
// connecting to db
$db = new USER_INFO_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO user_info(name, first_name, last_name, number, email, status, dob) VALUES('$name', '$first_name', '$last_name', '$number', '$email', '$status', '$dob')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "User successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
下面是MySQL数据库中数据库结构的快照。
这段代码的问题是,当我调试它时,查询永远不会成功运行,它总是得到以下输出“缺少必填字段”。这意味着缺少数字字段,但是为了进行实验,我什至在用户对象中对数字进行了硬编码。我真的一辈子都无法理解为什么参数没有被代码吸收。请帮忙。
我尝试直接从浏览器执行此查询以测试我的php文件。
http://115.118.217.53:8068/osachat_connect/create_user.php?name=Rayzone&firstname=Ray&number=97179&lastname=zone&email=a@b&status=hoqdy&dob=3/7/89
即使在这里我也得到了回应
create_user.php {"success":0,"message":"Required field(s) is missing"}
最佳答案
显然,您需要更好的调试技能,如果得到Required field(s) is missing
意味着不满足以下条件:
if (isset($_POST['number'])) {...}
因此,您应该找出android为什么不设置该参数的原因。
params.add(new BasicNameValuePair("number", number));
记录它:
Log.d("mylog", "number = " + number);
用PHP调试
error_log('**********************DEBUG************************');
ob_start();
var_dump($_POST);
$postBack = ob_get_contents();
ob_end_clean();
error_log($postBack);
error_log('**********************DEBUG************************');
试试我的功能:
public static String apiCaller(List<NameValuePair> params, url){
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String jsonString = null;
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity respEntity = response.getEntity();
if (respEntity != null) {
InputStream inputStream = respEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
jsonString = sb.toString();
Log.d(LOG_TAG, jsonString);
}
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
return jsonString;
}