1

JSON を使用して Android から PHP へのインターフェイスと PHP から Android への返信システムをテストしています。Android アプリから PHP ページに接続し、必要に応じてデータベースにエントリを作成しますが、PHP から Android への返信はゴミでいっぱいです。私は問題がどこにあるのだろうと思っていました:

//PHP
<?php 

require_once('functions.php');

$json = file_get_contents('php://input');
$obj = json_decode($json,true);



execute("insert into android_test (USERNAME,FULLNAME) values ('".$obj->{'UserName'}."', '".$obj->{'FullName'}."')"); //android_test (ID,IDUSERS,USERNAME,FULLNAME)
execute("commit");

  $posts = array($json);
  //$posts = array(1);

    header('Content-type: application/json');
    echo json_encode(array('posts'=>$posts));


?>

Android アプリ:

public void clickbuttonRecieve(View v) { //send to server
        try {
            JSONObject json = new JSONObject();
            json.put("UserName", "test2");
            json.put("FullName", "1234567");


            HttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams,
                    TIMEOUT_MILLISEC);
            HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
            HttpClient client = new DefaultHttpClient(httpParams);

            String url = "https://www.mypage.com/scripts/androidportalinput.php"; 

            HttpPost request = new HttpPost(url);
            request.setEntity(new ByteArrayEntity(json.toString().getBytes(
                    "UTF8")));
            request.setHeader("json", json.toString());


            HttpResponse response = client.execute(request); //get feedback
            HttpEntity entity = response.getEntity();
            // If the response does not enclose an entity, there is no need
            if (entity != null) {
                InputStream instream = entity.getContent();

                String result = RestClient.convertStreamToString(instream); //get feedback
                Log.i("Read from server", result);
                Toast.makeText(this,  result,
                        Toast.LENGTH_LONG).show();
            }
        } catch (Throwable t) {
            Toast.makeText(this, "Request failed: " + t.toString(),
                    Toast.LENGTH_LONG).show();
        }
    }

私が受け取るポップアップは「投稿」ですが、ページのhtmlコードも含まれているため、jsonでエンコードされたデータは完全にゴミであり、Androidアプリに送信されます。

これを解決するものはありますか?

助けてください

4

2 に答える 2

0

functions.php からデータを取得するために単純に ajax 呼び出しを使用しないのはなぜですか? functions.php が json 文字列を生成する場合は、このように進むことができます

$.ajax({

url : 'functions.php',

data : 'あなたの引数',

データタイプ: 'json',

成功: 関数 (取得) {

console.log(get.value);

}、

エラー: 関数 (e) {

console.log(e)

}

});

于 2013-12-15T08:52:32.433 に答える