gpt4 book ai didi

java - 无法将数据从 Android 应用程序发送到远程数据库

转载 作者:行者123 更新时间:2023-11-29 23:27:11 25 4
gpt4 key购买 nike

我想将注册表单数据从 Android 应用程序发送到远程 MySQL 数据库,但每次我都会收到相同的错误:

java.lang.String can not be converted to JSONObject.

这是我的代码:

JSONParser.java

`public class JSONParser 
{
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {
}
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) throws JSONException
{
try
{
// check for request method
if(method == "POST")
{
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.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);
HttpEntity httpEntity = httpResponse.getEntity();
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, "utf-8"), 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);
}
catch (JSONException e)
{
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return new JSONObject(json.substring(json.indexOf("{"),json.lastIndexOf("}") + 1));
}
}
`

这是我的 mainActivity 代码

class submitForm extends AsyncTask<String, String, String>
{

@Override
protected String doInBackground(String... args)
{
try
{
String first_name = mFirstname.getText().toString();
String last_name = mLastname.getText().toString();
String username = mUsername.getText().toString();
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
String mobile = mMobile.getText().toString();
String country = mCountry.getSelectedItem().toString();

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("FirstName", first_name));
params.add(new BasicNameValuePair("LastName", last_name));
params.add(new BasicNameValuePair("Username", username));
params.add(new BasicNameValuePair("Email", email));
params.add(new BasicNameValuePair("Password", password));
params.add(new BasicNameValuePair("Mobile", mobile));
params.add(new BasicNameValuePair("Country", country));

// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(
url_create_product, "POST", params);

// check log cat fro response
Log.d("Create Response", json.toString());

// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);

if (success == 1) {

// finish();
} else {
// failed to create product
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), " in catch",
Toast.LENGTH_LONG).show();

e.printStackTrace();
}

}
catch (Exception ex) {
Log.e("DIG", ex.toString());
}
return null;
}

}

这是我的 php 文件

<?php
// array for JSON response
header('Content-type=application/json; charset=utf-8');
$response = array();
$fname = $_POST['Firstname'];
$lname = $_POST['Lastname'];
$uname = $_POST['Username'];
$email = $_POST['Email'];
$password = $_POST['Password'];
$country = $_POST['Country'];
$mobile = $_POST['Mobile'];
// include db connect class
require_once ('db_connect.php');

// connecting to db
$db = new DB_CONNECT();

// mysql inserting a new row
$result = mysqli_query("INSERT INTO users(Firstname,Lastname,Username,Email,Password,Country,Mobile) VALUES('$fname', '$lname', '$uname', '$email', '$password', '$country', '$mobile')");

// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "User inserted successfully.";

// 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);
}
?>

在服务器端我收到错误未定义索引 名字、姓氏、用户名、电子邮件、密码...在 eclipse logcat 中我收到错误java.lang.string无法转换为JSONObject

最佳答案

您无法通过 POST 在 php 中访问该数据,因为它是通过 HTTP header 在 Android 应用程序上发送的,而不是通过 application/x-www-form-urlencoded 发送的。

这里有一个线程解释了如何做到这一点:

How to retrieve Request Payload

关于java - 无法将数据从 Android 应用程序发送到远程数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26867282/

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