php - 从 android 发布 JSON 数据时出错

标签 php android mysql json

我正在尝试使用 PHP 脚本将一些内容发布到我的 mysql 数据库。我用过JSON解析。当我单击按钮时,应用程序显示帖子已成功添加,但是当我发布更新时出现错误。我的 php 脚本工作正常,因为我已经在浏览器上检查过它。以下是类文件。

UpdateList.java

package com.example.test;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class UpdateList extends Activity implements OnClickListener{

    private EditText book, issue,returned;
    private Button  mSubmit;

     // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();


    //testing on Emulator:
    private static final String POST_COMMENT_URL = "http://crshaggy.byethost7.com/webservice/updateprofile.php";



    //ids
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.update_list);

        book = (EditText)findViewById(R.id.book);
        issue = (EditText)findViewById(R.id.issue);
        returned = (EditText)findViewById(R.id.returned);


        mSubmit = (Button)findViewById(R.id.button12);
        mSubmit.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
                new PostComment().execute();
    }


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

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(UpdateList.this);
            pDialog.setMessage("Posting on Profile...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
             // Check for success tag
            int success;
            String post_book = book.getText().toString();
            String post_issue = issue.getText().toString();
            String post_returned = returned.getText().toString();


            //We need to change this:
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(UpdateList.this);
            String post_username = sp.getString("username", "anon");

            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", post_username));
                params.add(new BasicNameValuePair("book", post_book));
                params.add(new BasicNameValuePair("issue", post_issue));

                params.add(new BasicNameValuePair("returned", post_returned));

                Log.d("request!", "starting");

                //Posting user data to script 
                JSONObject json = jsonParser.makeHttpRequest(
                        POST_COMMENT_URL, "POST", params);

                // full json response
                Log.d("Post Comment attempt", json.toString());

                // json success element
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("Comment Added!", json.toString());    
                    finish();
                    return json.getString(TAG_MESSAGE);
                }else{
                    Log.d("Comment Failure!", json.getString(TAG_MESSAGE));
                    return json.getString(TAG_MESSAGE);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;

        }

        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
            if (file_url != null){
                Toast.makeText(UpdateList.this, file_url, Toast.LENGTH_LONG).show();
            }

        }

    }


}

错误日志

Error parsing data org.json.JSONException: Value Failed of type java.lang.String cannot be converted to JSONObject

JSONParser.java

package com.example.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

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.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }


    public JSONObject getJSONFromUrl(final String url) {

        // Making HTTP request
        try {
            // Construct the client and the HTTP request.
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            // Execute the POST request and store the response locally.
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // Extract data from the response.
            HttpEntity httpEntity = httpResponse.getEntity();
            // Open an inputStream with the data content.
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            // Create a BufferedReader to parse through the inputStream.
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            // Declare a string builder to help with the parsing.
            StringBuilder sb = new StringBuilder();
            // Declare a string to store the JSON object data in string form.
            String line = null;

            // Build the string until null.
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            // Close the input stream.
            is.close();
            // Convert the string builder data to an actual string.
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // Try to 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 the JSON Object.
        return jObj;

    }


    // 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();
                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, "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);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

最佳答案

您应该传递 JSONObject 而不是字符串。这就是您必须传递 JSONObjects 的方式..

  JSONObject jsonObjSend = new JSONObject();

        try {
            jsonObjSend.put("username",userName.getText().toString().trim());
            jsonObjSend.put("password",userPhoneNumber.getText().toString().trim());

        } 
        catch (JSONException e) {
            e.printStackTrace();
        }

HTTPPOST

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;

        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Content-type", "application/json");
        httpPostRequest.setHeader("Accept-Charset", "utf-8");
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);

关于php - 从 android 发布 JSON 数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25197928/

相关文章:

php - 如何使用 php、mysql、css、jquery 和 html 创建简单的网站?

php - 参数化/配置 php 应用程序的最简单方法 |人性化的数据序列化

android - 按下向上按钮时的自定义 Activity 转换

android - savedInstanceState 在第一次应用程序关闭后为空,但在第二次关闭后不为空

mysql - 如何在 SQL Buddy 中使用外键?

php - Apache 读取 ZIP 文件而不是下载

android - 我如何在我的 Android 应用程序中看到完整的 ListView

c# - XmlAttributeCollection 无法从 xml 获取属性

mysql - 全文搜索工作针对艺术家而不是标题

php - ZF2 控制台路由无限参数