Waqas Khan
Waqas Khan

Reputation: 55

How to send json object to the webserver using post

I want to send json object to my webserver. I make some changes in previous version of code, where i was sending strings to my webserver. but it is not working for sending object. Please help!

package com.digitalapplication.eventmanager;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class BackgroundTask extends AsyncTask<JSONObject,Void,String> {
    Context ctx;
    BackgroundTask(Context ctx)
    {
        this.ctx=ctx;
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(JSONObject... params) {
        String inserturl="http://192.168.10.4/webapp/register.php";
        String method="register";
        if(method.equals("register"))
        {

            try {
                URL url=new URL(inserturl);
                HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                OutputStream OS=httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(OS,"UTF-8"));

                bufferedWriter.write(params.toString());

                bufferedWriter.flush();
                bufferedWriter.close();
                OS.close();
                InputStream IS=httpURLConnection.getInputStream();
                IS.close();
                return "Data Saved in server...";
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return "not saved in server";
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String  result) {
        Toast.makeText(ctx, result,Toast.LENGTH_SHORT).show();
    }


}


        return "not saved in server";
    }

here is call to the backgroundTask class

BackgroundTask backgroundTask=new BackgroundTask(this);

                JSONObject jsonObject=new JSONObject();
                try {
                    jsonObject.put("gid","asd");
                    jsonObject.put("uid","asdd");
                    jsonObject.put("name","assgd");
                    jsonObject.put("phone","agssd");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                backgroundTask.execute(jsonObject);

here is server side php script.

init.php

<?php
$db_name="eventmanager";
$mysql_user="root";
$mysql_pass="";
$server_name="localhost";
$con=mysqli_connect($server_name, $mysql_user,$mysql_pass,$db_name);
if(!$con){
    //echo"Connection Error...".mysqli_connect_error();
}
else{
    //echo"<h3>Connection success....</h3>";
}

?>

And

register.php

 <?php
    require "init.php";
    $obj = $_POST["obj"];
    $args = json_decode($obj, true);
    foreach($args as $key=>$field){
        $gid = $field["gid"];
        $uid = $field["uid"];
        $name = $field["name"];
        $phone = $field["phone"];
        $sql_query="insert into groups values('$gid','$uid','$name','$phone');";
        mysqli_query($con,$sql_query);

    }

    ?>

Upvotes: 0

Views: 1249

Answers (3)

Waqas Khan
Waqas Khan

Reputation: 55

At last I found the solution. I was missing following line of code which will encode my data before sending it to the server.

 String data= URLEncoder.encode("obj", "UTF-8") +"="+URLEncoder.encode(params[0].toString(), "UTF-8");

                bufferedWriter.write(data);

Upvotes: 0

Rosendo Ropher
Rosendo Ropher

Reputation: 498

Try using this method in your AsyncTask, this is a functional example.

// ......
private static final String USER_AGENT = "Mozilla/5.0";

public static String sendPost(String url, String data) throws Exception {

    HttpURLConnection  con = (HttpURLConnection) new URL(url).openConnection();

    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept","*/*");
    con.setRequestProperty("Content-Type","application/json");

    con.setDoOutput(true);
    con.setDoInput(true);

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(data);
    wr.flush();
    wr.close();
    data = null;

    System.out.println("\nSending 'POST' request to URL : " + url);

    InputStream it = con.getInputStream();
    InputStreamReader inputs = new InputStreamReader(it);

    BufferedReader in = new BufferedReader(inputs);
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }

    in.close();

    System.out.println("Server says : " + response.toString());
    return response.toString();
}

Your code looks well, but let's go to try with this. If this fails then, the problem is in your server.

If you have any output in your server please post it. Or you can too, print the values in your php script before the database insert, to see if really the values are arriving.

Upvotes: 1

JVXR
JVXR

Reputation: 1312

We'll need more than that, whats the error you are seeing ?

Edit if you see you are using ellipses as the param and calling toString on it. That will only give you an output like [Ljava.lang.String;@659e0bfd , which is not valid json. Try

params[0].toString()

and see if it works.

Upvotes: 1

Related Questions