gpt4 book ai didi

php - 无法从 Android 代码向 PHP 发送参数

转载 作者:行者123 更新时间:2023-11-29 12:09:46 24 4
gpt4 key购买 nike

我正在尝试开发一个简单的 Android 应用程序,将用户的信息存储到服务器上。所以我开发了我的应用程序的前端,并在我的服务器上创建了一个 MySql 数据库。我已经编写了更新数据库所需的 PHP 脚本,并且在 Android 代码中编写了一个解析器来解析数据并将数据发送到服务器。

问题是,我无法将参数从 Android 代码发送到 PHP 代码。我在 SO 和许多其他论坛上阅读了许多问题和答案,但似乎没有什么对我有用。请帮忙。

我创建了一个异步任务来执行将数据发送到服务器的任务。这是异步任务的代码。

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 数据库中数据库结构的快照。 This is a snapshot of the database structure in the MySQL Database.

此代码的问题是,当我调试它时,查询从未成功运行,它总是得到以下输出“缺少必需的字段”。这意味着数字字段丢失,但为了实验目的,我什至在用户对象中硬编码了数字。我真的无法理解为什么代码没有获取参数。请帮忙。

我尝试直接从浏览器执行此查询来测试我的 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"}

最佳答案

显然你需要更好的调试技巧,如果你得到缺少必需的字段意味着不满足以下条件:

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;
}

关于php - 无法从 Android 代码向 PHP 发送参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30899357/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com