将android JSONObject发布到PHP的问题

时间:2011-03-02 00:19:27

标签: php android json post

我无法获得一个简单的JSONObject的android POST,以显示在服务器上的$ _POST数据中。服务器是PHP 5.3.4,android端是SDK 8模拟器。我可以像往常一样发布一个简单的NameValuePair,但是当我切换到你在下面看到的JSONObject + StringEntity时,$ _POST数组显示{}。继续在我的测试php页面上运行下面的代码。它有一个$ _POST和$ _SERVER的var_dump,以及搜索其中一个预期的键('email')。你会看到我尝试了很多'ContentType',看看是不是问题。我甚至使用WireShark来验证客户端和服务器之间的TCP会话是否正常。 POST数据在那里,但它没有显示在服务器的变量中。我被困了...感谢您提供的任何帮助。

import java.io.InputStream;

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 org.apache.http.params.HttpConnectionParams;
import org.json.JSONObject;

import android.util.Log;

public class TestPOST {
    protected static void sendJson (final String email, final String pwd) {
        HttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
        HttpResponse response;
        String URL = "http://web-billings.com/testPost.php";
        try{
            HttpPost post = new HttpPost(URL);

            // NameValuePair That is working fine...
            //List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);  
            //nameValuePairs.add(new BasicNameValuePair("email", email));  
            //nameValuePairs.add(new BasicNameValuePair("password", pwd));  
            //post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            //Log.i("main", "P2DB - String entity 'se' = "+nameValuePairs.toString());

            JSONObject jObject = new JSONObject();
            jObject.put("email", email);
            jObject.put("password", pwd);
            StringEntity se = new StringEntity(jObject.toString());
            //se.setContentType("charset=UTF-8");
            se.setContentType("application/json;charset=UTF-8");
            //se.setContentType("application/json");
            //se.setContentType("application/x-www-form-urlencoded");

            post.setEntity(se);
            Log.i("main", "TestPOST - String entity 'se' = "+GetInvoices.convertStreamToString(se.getContent()));

            response = client.execute(post);  

            /*Checking response */
            if(response!=null){
                InputStream in = response.getEntity().getContent(); //Get the data in the entity
                String message = GetInvoices.convertStreamToString(in);
                Log.i("main", "P2DB - Connect response = "+message);
            }
        }
        catch(Exception e){
            e.printStackTrace();
            //createDialog("Error", "Cannot Establish Connection");
        }
    }
}

如果你愿意,这是testPost.php页面:

<?php
    echo "\r\n<pre>\r\n";
    var_dump("\$_POST = ", $_POST)."\r\n";
    echo '$_POST[\'email\'] = '.$_POST['email']."\r\n";
    var_dump("\$_SERVER = ", $_SERVER)."\r\n";
    echo '</pre>';
    die; 
?>  

3 个答案:

答案 0 :(得分:8)

从我所看到的,HttpPost.setEntity设置请求的主体,没有任何名称/值配对,只是原始发布数据。 $ _POST不查找原始数据,只查找名称值对,它将转换为哈希表/数组。您有两个选择...要么处理原始发布数据,要么格式化请求,使其包含名称值对。

Android / Java,名称值对示例:

HttpClient httpclient = new DefaultHttpClient();  
HttpPost httppost = new HttpPost("http://web-billings.com/testPost.php");  

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);  
nameValuePairs.add(new BasicNameValuePair("jsondata", se));  
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  

PHP中的原始帖子数据访问:

$json = file_get_contents('php://input');

答案 1 :(得分:4)

您将json字符串作为post变量的一个大值发布。因此,您需要在服务器上获取json字符串并将其转换为对象,然后才能从PHP访问json中的数据。

$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);

if( !empty($jsonObj)) { 
    try {
        $email = $jsonObj['email'];
        $password = $jsonObj['password'];
    }
}

答案 2 :(得分:4)

非常感谢Jeff Parker和Saurav确定以下问题:1)在android端设置名称/值对,或者2)解析PHP端的原始输入。因为他们的建议是原始代码的更清洁和运行版本。我在这个简化的副本中传入一个JSONObject,因为这就是我在实际代码中所做的事情,并且有许多事情要做,这使得它真的值得海洋,但这些是基本的工作部分:

public class TestPOST2 {
    protected static void sendJson (final JSONObject json) {
        HttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
        HttpResponse response;
        String URL = "http://web-billings.com/testPost.php";

        try{
            HttpPost post = new HttpPost(URL);

            // Create a NameValuePair out of the JSONObject + a name
            List<NameValuePair> nVP = new ArrayList<NameValuePair>(2);  
            nVP.add(new BasicNameValuePair("json", json.toString()));  

            // Hand the NVP to the POST
            post.setEntity(new UrlEncodedFormEntity(nVP));
            Log.i("main", "TestPOST - nVP = "+nVP.toString());

            // Collect the response
            response = client.execute(post);  

            /*Checking response */
            if(response!=null){
                InputStream in = response.getEntity().getContent(); //Get the data in the entity
            }
        }
        catch(Exception e){
            e.printStackTrace();
            //createDialog("Error", "Cannot Establish Connection");
        }
    }
}