1

アプリケーションがJSONオブジェクトの助けを借りてphpスクリプトと通信する小さなアプリケーションを構築しようとしています. GET Request テスト アプリケーションを正常に実装しましたが、投稿で JSON を使用すると問題が発生します。コードはエラーを生成しませんが、コードとの接続を介して何も送信されなかったことを意味する空の Array() を除いて、私の php スクリプトは何も返しません。

<?php  print_r($_REQUEST);  ?>

そして試してみました

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

json variable not found エラーで 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 ストリーム ダンプを次に示します。

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 エンティティはマルチパートでエンコードされたものである必要があります。このリンクを参照してください。文字列エンティティを使用していますが、これは正しくありません。これは、Web ページでフォームを送信したときにブラウザーが行うことをエミュレートする 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 に答える