0

I'm trying to POST data in JSON format to a script I have running PHP on my webserver. I have found this post: How to send data to a website using httpPost, app crashes.

Using the code he wrote (putting it on a separate thread first) I am able to post data to the PHP script, which accesses it by the $_POST variable. However, I wish to post my data in JSON format. I am guessing it would require me to post a raw stream of data to the server. What functions are available to achieve this? I would also need to post images as a stream of data to the PHP script so I think this solution will also help me in that area.

Additionally, what are the advantages of posting JSON to the server rather than using the method he used?

I am programming the client side in Java in conjunction with the Android SDK.

Any help would be appreciated.

1

1 Answer 1

0

I have a sample example for posting json data .

Have a look at this:

    public class LoginActivity extends Activity {

        private static final String TAG = "LoginActivity";

        private Context mContext;
        private Intent mIntent;
        private ProgressDialog pdLoading;

        private class LoginTask extends AsyncTask<Void, Void, String>
        {

                private ArrayList<NameValuePair> mParams = new ArrayList<NameValuePair>();
                private JSONArray mJArray = new JSONArray();
                private JSONObject mJobject = new JSONObject();
                private String jsonString = new String();

                @Override
                protected void onPreExecute() {
                        super.onPreExecute();
                        pdLoading.show();
                }

                @Override
                protected String doInBackground(Void... params) {

                        try {
                                mJobject.put("userName", "test");
                                mJobject.put("password", "test");
                                mJArray.put(mJobject);
                                mParams.add(new BasicNameValuePair("message", mJArray.toString()));

                                jsonString = WebAPIRequest.postJsonData("http://putyoururlhere.com/login.php?", mParams);

                        } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                                return null;
                        }
                        return jsonString;
                }

                @Override
                protected void onPostExecute(String result) {
                        super.onPostExecute(result);
                        pdLoading.dismiss();

                        if(result!=null)
                        {

/*                              try {
                                        mJobject = new JSONObject(jsonString);
                                        if(mJobject.getString("Success").equals("True"))
                                        {
                                                mJArray = mJobject.getJSONArray("user");
                                                JSONObject mUser = mJArray.getJSONObject(0);

                                        }
                                } catch (JSONException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                }*/

                                Log.e(TAG, jsonString);

                        }
                }

        }


        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                initialization();

                new LoginTask().execute();
        }

        private void initialization() {
                mContext = this;
                mIntent = new Intent();
                pdLoading = new ProgressDialog(mContext);
                pdLoading.setMessage("loading...");

        }


}

and

public class WebAPIRequest {


    public static String convertStreamToString(InputStream is)
                    throws IOException {
            if (is != null) {
                    StringBuilder sb = new StringBuilder();
                    String line;
                    try {
                            BufferedReader reader = new BufferedReader(
                                            new InputStreamReader(is, "UTF-8"));
                            while ((line = reader.readLine()) != null) {
                                    sb.append(line).append("\n");
                            }
                    } finally {
                            is.close();
                    }
                    return sb.toString();
            } else {
                    return "";
            }
    }


    public static String postJsonData(String url, List<NameValuePair> params) {
            String response_string = new String();

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            try {
                    httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));


                    String paramString = URLEncodedUtils.format(params, HTTP.UTF_8);
                    String sampleurl = url + "" + paramString;
                    Log.e("Request_Url", "" + sampleurl);

                    // Execute HTTP Post Request
                    HttpResponse response = httpclient.execute(httppost);
                    if (response != null) {
                            InputStream in = response.getEntity().getContent();
                            response_string = WebAPIRequest.convertStreamToString(in);

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

            return response_string;
    }

}

EDIT :

try,

print_r(json_decode($_POST['message'], true);  

or

$data = file_get_contents('php://input');
$json = json_decode($data,true);

I hope it will be helpful !!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer, I just want to clarify some things. It looks like you are sending the JSON string as a post key-value pair. So does this mean I need to access it via json_decode($_POST['message'])?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.