1

Hello guys I'm trying to sending my JSONArray to php page I'm getting HTTP//1.1 200 but I still can't show it in my php page and I still didn't know I have succeed to send it or not here is my android code

public void sendJson() {

                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
                HttpResponse response;

                try{
                    HttpPost post = new HttpPost("http://sap-sp-test.dff.jp/sp.php/ranking/index");
                    Log.i("entry", MixiActivity.entry.toString());

                    ArrayList<NameValuePair> nVP = new ArrayList<NameValuePair>(2);  
                    nVP.add(new BasicNameValuePair("json", MixiActivity.entry.toString()));
                    post.setEntity(new UrlEncodedFormEntity(nVP));
                    response = client.execute(post);
                    Log.i("postData", response.getStatusLine().toString());
                }
                catch(Exception e){
                    e.printStackTrace();
                    Log.i("error", e.getMessage());
                }

    }

PHP code

$data =  $_POST['json'];
echo $data;

I already tried some example here but I still can't sent the data and the JSON array(MixiActivity.entry) is not empty when I try to print it with log,the log show the right value of the JSON array but I just can't send it to the PHP please help me with this problem

Thanks a lot

Niko

2 Answers 2

2

You can try to add the encoding in post.setEntity() like this...

post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));

every thing else looks fine to me. If this doesn't work then you can also try to use the JSON library in android to directly encode it and pass that data to the page using

HttpPost httppost = new HttpPost("http://your/url/path/");  
httppost.addHeader("Content-Type", "application/json");
httppost.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));

Then in php you can access it by this code

$json = file_get_contents('php://input');
$obj = json_decode($json);
$name = $obj->{'name'};

Or

You can also try to make a get request or accessing data through $_REQUEST in your php file. Whatever you are using is exactly what is required.

or

Try this this is a working code... It is a class which you can directly use to pass data to your file. Call the function statically using :: , and import all the required json clases

public class RestClient {

private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    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();
        }
    }

    return sb.toString();
}




public static String connectSend(){

    /*
    HttpParams httpparams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpparams, 30000);
    HttpConnectionParams.setSoTimeout(httpparams, 30000);
    */

    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost("http://path/to/your/php/file");   

    httppost.addHeader("Content-Type", "application/json");

    JSONObject json = new JSONObject();
    try {
        json.put("item0", "data0");
        json.put("item1", "data1");
        json.put("item2", "data2");
        json.put("item3", "data3");
    } catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }


    try {
        httppost.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
        //httppost.setHeader("json", json.toString());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            String result = RestClient.convertStreamToString(instream);


            return result;
        }


    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return e.toString();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return e.toString();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return e.toString();
    } 
    catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    return "false";

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

5 Comments

Sorry mariachi I've tried both but I still can't post the JSON array any other idea?thanks
what is your response from response.getStatusLine().toString() and which one of my suggestions did you try?
I used your second suggestions and it return HTTP/1.1 200 OK and I've also tried your first suggestions and it return the same response,what do you think about it?
sorry mariachi but your code didn't work for me I use this on the PHP side $json = file_get_contents('php://input'); $obj = json_decode($json); $name = $obj->{'item0'}; echo $json; echo $obj; echo $name; print_r($json); print_r($obj); print_r($name); but none was printed or echoed is there any permission I missed? thanks
and in my friend's iphone program(there is also an iphone version of this) it's working, he is using a simple HTTPpost like I'm using in my question
1

Finally I gave up with http post in android now I'm using javascript to get the jsonarray from android

with this

public class JavaScriptInterface { Context mContext;

         JavaScriptInterface(Context c) {
             mContext = c;
         }

         public String load() {
             String JS = JsonArray.toString();
             return JS;
         } }

and in the HTML

 function loadJSON()        
{           
var jsonData = Android.load();
var myDictionary = [];          
myDictionary["jsonData"] = jsonData;

post(myDictionary, "http://sap-sp-test.dff.jp/sp.php/ranking/index?user_id=" + user_id+"&display_name=" + display_name + "&photo=" + photo +"&device=android", "post");         
}

for the post to PHP I'm using form POST in the javascript

function post(dictionary, url, method) 
        {
            method = method || "post"; // post (set to default) or get

            // Create the form object
            var form = document.createElement("form");
            form.setAttribute("method", method);
            form.setAttribute("action", url);

            // For each key-value pair
            for (key in dictionary) {
                //alert('key: ' + key + ', value:' + dictionary[key]); // debug
                var hiddenField = document.createElement("input");
                hiddenField.setAttribute("type", "hidden"); // 'hidden' is the less annoying html data control
                hiddenField.setAttribute("name", key);
                hiddenField.setAttribute("value", dictionary[key]);
                form.appendChild(hiddenField); // append the newly created control to the form
            }

            document.body.appendChild(form); // inject the form object into the body section
            form.submit();
        }

and in the PHP for receiving the json

if($this->_getParam('device') == "android")
        {
            $data = $_POST["jsonData"];
            $data = stripslashes($data);
            $friends = $data;
        }

and this method works for me anyway thanks mariachi for your help

Comments

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.