如何使用Android通过POST请求发送JSON对象

时间:2012-04-30 22:07:39

标签: android json client-server

我正在尝试构建一个小应用程序,其中应用程序将在JSON对象的帮助下与php脚本进行通信。我成功实现了GET请求测试应用程序,但在帖子中使用JSON会产生问题。代码生成没有错误,但我的PHP脚本回复没有任何东西,除了一个空的Array(),暗示没有通过代码连接发送任何东西:

<?php  print_r($_REQUEST);  ?>

并尝试

<?php  print($_REQUEST['json']); ?>

将HTML返回到应用程序,找不到json变量错误。

我已经尝试过这里提到的一些解决方案,包括:How to send a JSON object over Request with Android?How to send a json object over httpclient request with android所以如果你能指出我的错误并且可以简单地描述一下我做错了什么,那就太棒了。感谢。

以下是将JSON对象转换为字符串然后附加到Post变量的代码片段。

        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppostreq = new HttpPost(wurl);
        StringEntity se = new StringEntity(jsonobj.toString());
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httppostreq.setEntity(se);
            //httppostreq.setHeader("Accept", "application/json");
        //httppostreq.setHeader("Content-type", "application/json");
        //httppostreq.setHeader("User-Agent", "android");
        HttpResponse httpresponse = httpclient.execute(httppostreq);
        HttpEntity resultentity = httpresponse.getEntity();

这是通过wireshark收集的TCP Stream Dump,如果它可以提供帮助:

POST /testmysql.php?test=true HTTP/1.1
Content-Length: 130
Content-Type: application/json;charset=UTF-8
Content-Type: application/json;charset=UTF-8
Host: 192.168.100.4
Connection: Keep-Alive
User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.4)
{"weburl":"hashincludetechnology.com","header":{"devicemodel":"GT-I9100","deviceVersion":"2.3.6","language":"eng"},"key":"value"}HTTP/1.1 200 OK
Date: Mon, 30 Apr 2012 22:43:10 GMT
Server: Apache/2.2.17 (Win32)
Content-Length: 34
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html
Array
(
    [test] => true
)
Test // echo statement left intentionally.

3 个答案:

答案 0 :(得分:1)

您在服务器端使用PHP,因此您的HTTP实体必须是多部分编码的。见this link。您正在使用字符串实体,但这不正确。它必须是MultipartEntity,它模拟了在网页中提交表单时浏览器的功能。 MultipartEntity应该在httpmime jar中。

获得多部分实体后,只需添加名为“json”的部件,并将其内容设置为json编码对象的字符串表示形式。

请注意,这个答案是因为您在服务器端使用PHP,因此您必须使用其“协议”通过$ _REQUEST读取变量。如果您在服务器端使用自己的请求解析器,即使是StringEntity也可以。见HTTP_RAW_POST_DATA

答案 1 :(得分:1)

以下应该有效。确保为您的表单帖子在顶部设置适当的键。我还包括如何发送图像以及其他各种json数据,如果没有必要,只需删除这些行。

static private String postToServerHelper(
            String action,
            JSONObject jsonData,
            byte[] imageData){

        // keys for sending to server
        /** The key for the data to post to server */
        final String KEY_DATA = "data";
        /** The key for the action to take on server */
        final String KEY_ACTION = "action";
        /** The return code for a successful sync with server */
        final int GOOD_RETURN_CODE = 200;
        /** The key for posting the image data */
        final String KEY_IMAGE = "imageData";
        /** The image type */
        final String FILE_TYPE = "image/jpeg";
        /** The encoding type of form data */
        final Charset ENCODING_TYPE = Charset.forName("UTF-8");

        // the file "name"
        String fileName = "yourFileNameHere";

        // initialize result string
        String result = "";

        // initialize http client and post to correct page
        HttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://www.yourdomain.com/yourpage.php");

        // set to not open tcp connection
        httpPost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

        // build the values to post, the action and the form data, and file data (if any)
        MultipartEntity multipartEntity = new MultipartEntity(
                HttpMultipartMode.BROWSER_COMPATIBLE);
        try{
            multipartEntity.addPart(KEY_ACTION, new StringBody(action, ENCODING_TYPE));
            multipartEntity.addPart(KEY_DATA, new StringBody(jsonData.toString(), ENCODING_TYPE));
            if (imageData != null){
                multipartEntity.addPart(KEY_IMAGE, new ByteArrayBody(imageData, FILE_TYPE, fileName));
            }
        }catch (Exception e){
            return e.getMessage();
        }

        // set the values to the post
        httpPost.setEntity(multipartEntity);

        int statusCode= -1;

        // send post
        try {
            // actual send
            HttpResponse response = client.execute(httpPost);

            // check what kind of return
            StatusLine statusLine = response.getStatusLine();
            statusCode = statusLine.getStatusCode();

            // good return
            if (statusCode == GOOD_RETURN_CODE) {
                // read return
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                        builder.append(line + "\n");
                }
                content.close();
                result = builder.toString();

                // bad return   
            } else {
                return String.parse(statusCode);
            }

            // different failures   
        } catch (ClientProtocolException e) {
            return e.getMessage();
        } catch (IOException e) {
            return e.getMessage();
        }

        // return the result
        return result;  
    }

答案 2 :(得分:0)

DefaultHttpClient httpClient = new DefaultHttpClient();                 HttpPost httpPost = new HttpPost(url);

            JSONObject clientList = new JSONObject ();
            clientList.put("name","");
            clientList.put("email","");
            clientList.put("status","");
            clientList.put("page","");



            JSONObject listclient = new JSONObject ();
            listclient.put("mydetail", clientList);

   //--List nameValuePairs = new ArrayList(1);
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("token", tokenid));
            nameValuePairs.add(new BasicNameValuePair("json_data", listclient.toString()));


            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            Log.d("JSON",nameValuePairs.toString());

            //-- Storing Response
            HttpResponse httpResponse = httpClient.execute(httpPost);