Isuru Madusanka
Isuru Madusanka

Reputation: 373

json post request java not send data to server

I try to Create a class which is unique to all json request and try to send json request from it to server. It takes only request url and json StringEntity only. Request send but problem is when i try to access data from server can't find that post data.

JSONClinet.java

package info.itranfuzz.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class JSONClient {

    private final HttpClient httpClient;
    private HttpPost httpPost;
    private HttpResponse httpResponse;

    public JSONClient() {
        httpClient = new DefaultHttpClient();
    }

    public String doPost(String url, StringEntity se) {

        InputStream inputStream = null;
        String result = "";

        httpPost = new HttpPost(url);

        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        httpPost.setEntity(se);
        try {
            httpResponse = httpClient.execute(httpPost);
            inputStream = httpResponse.getEntity().getContent();
            if (inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";
        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }
        return result;
    }

    private static String convertInputStreamToString(InputStream inputStream)
            throws IOException {
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }

}

Server accss code is here. There email and lat and lng to send to server.

<?php

//set content type to json
        header('Content-type: application/json');

        $email = $this->input->post("email");
        $lat = $this->input->post('lat');
        $lng = $this->input->post('lng');

        $status = array("STATUS"=>"false");
        if($this->donor->updateLocationByEmail($email,$lat,$lng)){
            $status = array("STATUS"=>"true");
        }
        array_push($status, array("email"=>$email,"lat"=>$lat,"lng"=>$lng));
        echo json_encode($status);

?>

My calling method is this

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        JSONClient jClient = new JSONClient();

        Location loc = new Location(LocationService.this);
        LatLng p = loc.getLocation();

        if (p != null) {
            String json = "";

            try {
                JSONObject jsonObject = new JSONObject();
                // jsonObject.accumulate("email", WebLoad.STORE.getEmail());
                jsonObject.put("email", "[email protected]");
                jsonObject.put("lat", p.getLat());
                jsonObject.put("lng", p.getLng());

                json = jsonObject.toString();

                System.out.println(jClient.doPost(WebLoad.ROOTURL
                        + "/donor_controller/updatelocation", new StringEntity(
                        json)));

            } catch (JSONException e) {
                System.out.println("Json exception occur");
            } catch (UnsupportedEncodingException e) {
                System.out.println("Unsupported ecodding exception occur");
            }

        }
        return super.onStartCommand(intent, flags, startId);
    }

Upvotes: 0

Views: 874

Answers (2)

uma
uma

Reputation: 1577

//import packages


public class DBConnection {

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

// This is a constructor of this class
public DBConnection() {

}

/*
 * function get jsonObject from URL by making HTTP POST or GET method.
 */

public JSONObject createHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request

    try {
        // check for request method
        if (method == "POST") {
            // request method is POST and making default client.
            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 ex) {
        ex.printStackTrace();
    } catch (ClientProtocolException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.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();
        Log.w("Error" ,"My Error" + json);
    } catch (Exception ex) {
        Log.e("Buffer Error", "Error converting result " + ex.toString());
    }

    // try to parse the string to a JOSN object
    try {

        Log.w("sub",json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
        jsonObject = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));

    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return new object
    return jsonObject;

}

}

please , you try this manner to make request.

Upvotes: 1

uma
uma

Reputation: 1577

$email = $this->input->$_POST('email')

use this way any try to do . change post to $_POST['variable name']. as i tell this , you write to server side PHP. in PHP get and post method we access $_GET and $_POST.

Upvotes: 0

Related Questions