2

I want to send data from android app to remote server. I have tried to send data as a sample to the server but it is working. I am uploading my code below. I am not sure but may be my data sending formate is wrong.

The link need to show a success message. Unfortunately it not showing any change.

public void postData() throws JSONException {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://192.168.1.145/tracker/index.php/json/add_task");
    JSONObject json = new JSONObject();

    try {
        // JSON data:
        json.put("task_title", "Fahmi Rahman");
        json.put("task_details", "sysdev");

        JSONArray postjson=new JSONArray();
        postjson.put(json);

        // Post the data:
        httppost.setHeader("json",json.toString());
        httppost.getParams().setParameter("jsonpost",postjson);

        // Execute HTTP Post Request
        System.out.print(json);
        HttpResponse response = httpclient.execute(httppost);

        // for JSON:
        if(response != null)
        {
            InputStream is = response.getEntity().getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();

            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //text = sb.toString();
        }

        //tv.setText(text);

    }catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
}

And I need to send data this formate

{"task":{
            "task_title":"All json formate",
            "task_details":"View All task list, View task list by user id, Add new task"}}
Ali Khaki
  • 1,184
  • 1
  • 13
  • 24

4 Answers4

2

JsonObject formatting:

Assign new Inner JsonObject

JSONObject jInnerObject = new JSONObject();

Insert key and value in Inner JsonObject

jInnerObject.put("task_title", "Fahmi Rahman");
jInnerObject.put("task_details", "sysdev");

Assign new Outer JsonObject

JSONObject jOuterObject = new JSONObject();

Insert Inner object with key in Outer object

jOuterObject.put("task", jInnerObject);
Log.i("JSonServerObject", jOuterObject.toString());

Done

Hiren Patel
  • 52,124
  • 21
  • 173
  • 151
  • Hi I am having this kind of same issue http://stackoverflow.com/questions/35895134/getting-false-response-while-post-response-to-server-using-volley.can you please check that. – Stephen Apr 01 '16 at 08:22
0

try using the below code

public String POSTconnection(String postjson) {
        String output = null;
        try {

        //init your hhtp client
        HttpClient httpclient = new DefaultHttpClient();

        //init your http post
        HttpPost httpPost = new HttpPost(Constant.URL + url);

        //consider name value pair as post parameters kinda like key and value
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

        //add the new parameter with key jsonpost and post json as a value
        nameValuePairs.add(new BasicNameValuePair("jsonpost",postjson));


        // add parameters to your request 
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));

        //excute the request

        HttpResponse httpResponse = httpclient.execute(httpPost);


        HttpEntity httpEntity = httpResponse.getEntity();
        output = EntityUtils.toString(httpEntity,"UTF-8");

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();
    }

    return output;
}
Ahmed Basyouny
  • 343
  • 3
  • 11
0
This is the code


    public class MainActivity extends AppCompatActivity {
    private String TAG="";
    private EditText n,m,p,d;private String name,password,mobile,doctor;
    InputStream inputStream;OutputStream outputStream;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        n=(EditText)findViewById(R.id.editText1);
        p=(EditText)findViewById(R.id.editText2);
        m=(EditText)findViewById(R.id.editText3);
        d=(EditText)findViewById(R.id.editText4);
        // Button b=(Button)findViewById(R.id.button);
    }
    public void button(View   v) {
        name = n.getText().toString().trim();
        password = p.getText().toString().trim();
        mobile = m.getText().toString().trim();
        doctor= d.getText().toString().trim();
        new SendPostRequest().execute();
    Intent i=new Intent(MainActivity.this,Main2Activity.class);
        startActivity(i);
    }
    class SendPostRequest extends AsyncTask<String, Void, String> {

        protected void onPreExecute() {
        }

        protected String doInBackground(String... arg0) {

            try {


                try {  URL url = new URL("http://**********.php");

                    JSONObject postDataParams = new JSONObject();
                    postDataParams.put("Name", name);
                    postDataParams.put("Password", password);
                    postDataParams.put("Mobile", mobile);
                    postDataParams.put("DoctorID", doctor);
                    Log.d(TAG, "doInBackground: "+postDataParams );
                    HttpURLConnection  httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setDoInput(true);
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setRequestMethod("POST");
                    outputStream = httpURLConnection.getOutputStream();
                    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
                    bufferedWriter.write(String.valueOf(postDataParams));
                    bufferedWriter.flush();
                    int statusCode = httpURLConnection.getResponseCode();
                    Log.d("this", " The status code is " + statusCode);
                    if (statusCode == 200)
                    {
                        inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
                        String response =  convertInputStreamToString(inputStream);
                        Log.d("this", "The response is " + response);
                        JSONObject jsonObject = new JSONObject(response);
                        return response;
                    }
                    else { return null; }
                }
                catch (Exception e)
                { e.printStackTrace(); }
                finally
                {
                    try { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } catch (Exception e) { e.printStackTrace(); } }
            } catch (Exception e) {
                return new String("Exception: " + e.getMessage());
            }
            return null;
        }


        @Override
        protected void onPostExecute(String result) {

        }
        private String convertInputStreamToString(InputStream inputStream)
        { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String line = null;
            try { while ((line = reader.readLine()) != null)
            { sb.append(line).append('\n'); } }
            catch (IOException e) { e.printStackTrace(); }
            finally { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); }

    }



}
Nischitha s
  • 1
  • 4
  • 9
0

use volley Lab. & use following sample code

 RequestQueue queue = Volley.newRequestQueue(this);

 private void serverFronJsonObjReq() {
 showProgressDialog();


    Map<String, String> postParam= new HashMap<String, String>();
    postParam.put("username", "singh@gmail.com");
    postParam.put("password", "123456");


 JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
    Const.BASE_URL_LOGIN, new JSONObject(postParam),
    new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            Log.d(TAG, response.toString());
            msgResponse.setText(response.toString());
            hideProgressDialog();
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            hideProgressDialog();
        }
    }) {

/**
  Passing some request headers
 * */
  @Override
  public Map<String, String> getHeaders() throws AuthFailureError {
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("Content-Type", "application/json; charset=utf-8");
    return headers;
}



  };

 jsonObjReq.setTag(TAG);
 // Adding request to request queue
 queue.add(jsonObjReq);

 // Cancelling request
 /* if (queue!= null) {
  queue.cancelAll(TAG);
 } */

}
Sudhir Singh
  • 817
  • 11
  • 16