1

我正在尝试构建一个小型应用程序,其中应用程序将在 JSON 对象的帮助下与 php 脚本进行通信。我成功地实现了 GET 请求测试应用程序,但是使用带有 post 的 JSON 会产生问题。该代码没有产生错误,但我的 php 脚本回复除了一个空的 Array() 之外什么都没有,这意味着没有通过代码的连接发送任何内容:

<?php  print_r($_REQUEST);  ?>

并尝试

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

使用未找到 json 变量的错误将 HTML 扔回应用程序。

我已经尝试过这里提到的一些解决方案,包括:How to send a JSON object over Request with Android? 以及如何使用 android 通过 httpclient 请求发送 json 对象,所以如果您能指出我的错误并简要描述我到底做错了什么,那就太好了。谢谢。

这是 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.
4

3 回答 3

1

您在服务器端使用 PHP,因此您的 HTTP 实体必须是多部分编码的实体。请参阅此链接。您正在使用字符串实体,但这是不正确的。它必须是 MultipartEntity,它模拟您在网页中提交表单时浏览器所做的事情。MultipartEntity 应该在 httpmime jar 中。

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

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

于 2012-04-30T22:30:40.053 回答
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;  
    }
于 2012-04-30T22:44:10.297 回答
0

DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = 新的 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);
于 2012-05-01T10:11:20.807 回答