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

时间:2014-11-11 14:34:15

标签: java php android mysql

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

  

java.lang.String无法转换为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);
}
?>

在服务器端我收到错误 undefined index名字,姓氏,用户名,电子邮件,密码...... 并在eclipse logcat中我得到错误 java.lang.string无法转换为JSONObject

1 个答案:

答案 0 :(得分:0)

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

这是一个解释如何做到这一点的线程:

How to retrieve Request Payload