如何将JSONObject传递给PHP文件?

时间:2011-05-28 20:46:52

标签: java android json httpclient

我正在尝试将一些格式化为JSONObject的数据提交到Web服务器。我的理解是这是通过android上的httpclient和服务器上的php文件完成的。如果不是这种情况停在这里并纠正我,否则这就是我试图发送数据的方式:

HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://myhost/data.php");
            try {
                String UN = username.getText().toString();
                String PW = password.getText().toString();
                String jString = "{\"login\": { \"username\": \""+UN + "\",\"password\": \""+PW+"\"}}";
                JSONDATA = new JSONObject(jString);
                //JSONDATA = new JSONObject();
                //JSONDATA.put("username", UN);
                //JSONDATA.put("password", PW);

我应该使用:httppost.setEntity(new UrlEncodedFormEntity(JSONDATA));

或者我应该这样做:

                StringEntity se = new StringEntity(JSONDATA.toString());  
                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                HttpEntity entity;
                entity = se;
                httppost.setEntity(entity);
                HttpResponse response;
                response = httpclient.execute(httppost);

1 个答案:

答案 0 :(得分:3)

问题是你打算如何在服务器上提取数据?你的PHP是什么样的?最简单的方法是将JSON作为参数传递:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myhost/data.php");
try {
   String UN = username.getText().toString();
   String PW = password.getText().toString();
   String jString = "{\"login\": { \"username\": \""+UN + "\",\"password\":\""+PW+"\"}}";
   List <NameValuePair> nvps = new ArrayList <NameValuePair>();
   nvps.add(new BasicNameValuePair("value", jString));
   httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));                 

   HttpResponse response;
   response = httpclient.execute(httppost);

然后在服务器端你可以做

<?php
   $obj = json_decode($_POST['value']);

检索它。