2013-03-10 5 views
0

Я сводил к простейшей форме и все еще спотыкаюсь ... Я провел более 30 часов исследований и испытаний. По всем постам, которые никогда не показывают больше 15 ° всего круга, это должно быть очень легко.JSON полный круг (PHP)

Я хочу:

  1. параметры Отправить запрос (в формате JSON) из телефона Android на сервер WAMP ... Это может быть как полный дамп локальной таблицы SQLite, поэтому строки запроса просто не отрежет.
  2. Есть сервер WAMP читать данные в формате JSON, формулировать запрос SQL и представить в базу данных MySql
  3. Пакет ответа в данных JSON (от простого «OK» для полного дампа таблицы)
  4. Вернуться ответ пакет на телефон Android

Это уже полностью функциональное приложение WAMP, и я хочу интегрировать Android-доступ. По этой причине я действительно хочу избежать AJAX, так как хочу поддерживать согласованность с тем, что уже на месте.

Я уменьшил это до простейшего цикла и попал в коряги. Я использую send.php для отправки некоторых данных JSON на get.php. На данный момент мне просто нужно получить.php, чтобы прочитать данные и отправить их обратно (слегка измененный) на send.php

send.php правильно читает запас JSON, отправленный из receive.php. Я просто не могу получить никаких признаков жизни, которые receive.php даже признает отправленный JSON.

ПОЖАЛУЙСТА, не направляйте меня в направлении cURL ... из всего, что я нашел в отношении Android и JSON, cURL - это тангенс, который вернет мне полный круг обратно в нефункциональность.

APACHE 2.2.22, PHP 5.4.3

Как я уже сказал, я свел к простейшей форме, чтобы продемонстрировать полный круг ...

send.php:

<?php 
$url = "http://192.168.0.102:808/networks/json/receive.php"; 
$data = array(
     'param1'  => '12345', 
     'param2' => 'fghij' 
); 
$json_data = json_encode($data); 

$options = array(
     'http' => array(
       'method' => 'POST', 
       'content' => $json_data, 
       'header'=> "Content-Type: application/json\r\n" . 
       "Accept: application/json\r\n" . 
       'Content-Length: ' . strlen($json_data) . "\r\n" 
     ) 
); 

$context = stream_context_create($options); 
$result = file_get_contents($url, false, $context); 

$response = json_decode($result , true); 
echo '[' . $response['param1'] . "]\n<br>"; 
//THIS WORKS! send.php displays "Initialized" 
?> 

receive.php

<?php 
$newparam = 'Initialized'; 
//HERE I NEED TO read the JSON data and do something 

$data = array(
     'param1'  => $newparam, 
     'param2' => 'pqrst' 
); 

header('Content-type: application/json'); 
echo json_encode($data); 
?> 
+0

Внутри использования receive.php 'error_log () 'искать признаки жизни. – mkaatman

+0

@ user2147564 Попробуйте json_decode ($ data), когда вы читаете (в приеме.php) данные JSON, которые были отправлены. – kalaero

+0

isset ($ _ POST) возвращает true, но, похоже, ничего не содержит. Если я попытаюсь получить доступ к $ _POST ['content'], который кажется логичным из отправленного отправителя _by_ send.php, там ничего нет (ошибка). Я знаю, что мне нужно json_decode ($ data_from_send_php), но как я могу получить входящие данные JSON? – Chameleon

ответ

0

Это на самом деле легко, как указано во всех неполных объяснений ... Я получил полный круг для работы finally

Я выбрал простоту, чтобы доказать, что могу путешествовать по кругу, и теперь я это сделал.

send.php

<?php 
//The URL of the page that will: 
// 1. Receive the incoming data 
// 2. Decode the data and do something with it 
// 3. Package the results into JSON 
// 4. Return the JSON to the originator 
$url = "http://192.168.0.102:808/networks/json/receive.php"; 

//The JSON data to send to the page (above) 
$data = array(
     'param1'  => 'abcde', 
     'param2' => 'fghij' 
); 
$json_data = json_encode($data); 

//Prep the request to send to the web site 
$options = array(
     'http' => array(
       'method' => 'POST', 
       'content' => $json_data, 
       'header'=> "Content-Type: application/json\r\n" . 
       "Accept: application/json\r\n" 
     ) 
); 
$context = stream_context_create($options); 

//Make the request and grab the results 
$result = file_get_contents($url, false, $context); 

//Decode the results 
$response = json_decode($result , true); 

//Do something with the results 
echo '[' . $response['param1'] . "]\n<br>"; 
?> 

receive.php

<?php 
//K.I.S.S. - Retrieve the incoming JSON data, decode it and send one value 
//back to send.php 

//Grab the incoming JSON data (want error correction) 
//THIS IS THE PART I WAS MISSING 
$data_from_send_php = file_get_contents('php://input'); 

//Decode the JSON data 
$json_data = json_decode($data_from_send_php, true); 

//CAN DO: read querystrings (can be used for user auth, specifying the 
//requestor's intents, etc) 

//Retrieve a nugget from the JSON so it can be sent back to send.php 
$newparam = $json_data["param2"]; 

//Prep the JSON to send back 
$data = array(
     'param1'  => $newparam, 
     'param2' => 'pqrst' 
); 

//Tell send.php what kind of data it is receiving 
header('Content-type: application/json'); 

//Give send.php the JSON data 
echo json_encode($data); 
?> 

И интеграция Android ... вызывается с Button.onClickListener

public void getServerData() throws JSONException, ClientProtocolException, IOException { 
    //Not critical, but part of my need...Preferences store the pieces to manage JSON 
    //connections 
    Context context = getApplicationContext(); 
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); 
    String netURL = prefs.getString("NetworkURL", ""); 
    // "http://192.168.0.102:808/networks/json" 
    String dataPage = prefs.getString("DataPage", ""); 
    // "/receive.php" 

    //NEEDED - the URL to send to/receive from... 
    String theURL = new String(netURL + dataPage); 

    //Create JSON data to send to the server 
    JSONObject json = new JSONObject(); 
    json.put("param1",Settings.System.getString(getContentResolver(),Settings.System.ANDROID_ID)); 
    json.put("param2","Android Data"); 

    //Prepare to commnucate with the server 
    DefaultHttpClient httpClient = new DefaultHttpClient(); 
    ResponseHandler <String> resonseHandler = new BasicResponseHandler(); 
    HttpPost postMethod = new HttpPost(theURL); 

    //Attach the JSON Data 
    postMethod.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8"))); 

    //Send and Receive 
    String response = httpClient.execute(postMethod,resonseHandler); 

    //Begin reading and working with the returned data 
    JSONObject obj = new JSONObject(response); 

    TextView tv_param1 = (TextView) findViewById(R.id.tv_json_1); 
    tv_param1.setText(obj.getString("param1")); 
    TextView tv_param2 = (TextView) findViewById(R.id.tv_json_2); 
    tv_param2.setText(obj.getString("param2")); 
    } 
Смежные вопросы