8

文字列配列を POST データとして PHP スクリプトに渡そうとしていますが、どうすればよいかわかりません。

これまでにPHPスクリプトを実行するための私のコードは次のとおりです。

配列を渡そうとしているところ:

nameValuePairs.add(new BasicNameValuePair("message",message));
String [] devices = {device1,device2,device3};
nameValuePairs.add(new BasicNameValuePair("devices", devices));// <-- Can't pass String[] to BasicNameValuePair
callPHPScript("notify_devices", nameValuePairs);

PHP スクリプトを呼び出します。

public String callPHPScript(String scriptName, List<NameValuePair> parameters) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://localhost/" + scriptName);
    String line = "";
    StringBuilder stringBuilder = new StringBuilder();
    try {
        post.setEntity(new UrlEncodedFormEntity(parameters));

        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() != 200)
        {
            System.out.println("DB: Error executing script !");
        }
        else {
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent()));
            line = "";
            while ((line = rd.readLine()) != null) {
                stringBuilder.append(line);
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("DB: Result: " + stringBuilder.toString());
    return stringBuilder.toString();
}

問題の PHP スクリプトは次のとおりです。

<?php
include('tools.php');
// Replace with real BROWSER API key from Google APIs
$apiKey = "123456";

// Replace with real client registration IDs 
$registrationIDs = array($_POST[devices]); <-- Where I want to pass array to script

// Message to be sent
$message = $_POST['message'];

// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';

$fields = array(
                'registration_ids'  => $registrationIDs,
                'data'              => array( "message" => $message ),
                );

$headers = array( 
                    'Authorization: key=' . $apiKey,
                    'Content-Type: application/json'
                );

// Open connection
$ch = curl_init();

// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $url );

curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );

// Execute post
$result = curl_exec($ch);

// Close connection
curl_close($ch);

print_as_json($result);
?>

何か案は?ありがとう !

編集

私は次のことを試みていますが、まだ喜びはありません:

public void notifyDevices(Message message) {

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    List<String> deviceIDsList = new ArrayList<String>();
    String [] deviceIDArray;

    //Get devices to notify
    List<JSONDeviceProfile> deviceList = getDevicesToNotify();

    for(JSONDeviceProfile device : deviceList) {
        deviceIDsList.add(device.getDeviceId());
    }

    //Array of device IDs
    deviceIDArray = deviceIDsList.toArray(new String[deviceIDsList.size()]);
    for(String deviceID : deviceIDArray) {

        nameValuePairs.add(new BasicNameValuePair("devices[]", deviceID));

    }

    //Call script
    callPHPScript("GCM.php", nameValuePairs);
}

これは私が持っているすべての「エラー報告」です...

        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() != 200)
        {
            System.out.println("DB: Error executing script !");
        }
4

3 に答える 3

20

クエリ文字列で配列をphpに渡すには、[]識別子に追加し、すべての項目を個別のエントリとして追加する必要があるため、次のようなものが機能するはずです:

nameValuePairs.add(new BasicNameValuePair("devices[]", device1));
nameValuePairs.add(new BasicNameValuePair("devices[]", device2));
nameValuePairs.add(new BasicNameValuePair("devices[]", device3));

これで$_POST['devices']、php 側に配列が含まれます。

于 2013-04-06T13:51:08.833 に答える
5

デバイス配列を json エンコードして、BasicNameValuePair(...) に渡すことができる文字列を取得する必要があると思います。PHP コードでは、json_decode を使用して配列を取得するだけです。

JSONArray devices = new JSONArray();
devices.put(device1);
devices.put(device2);
devices.put(device3);

String json = devices.toString();
nameValuePairs.add(new BasicNameValuePair("devices", devices));

あなたのphpコードで:

$devices = $_POST['devices'];
$devices = json_decode($devices);
于 2013-04-06T13:41:59.583 に答える
2

$_POSTまず、 PHP で配列にアクセスするときに一重引用符がありません。行を変更する

$registrationIDs = array($_POST[devices]);

に:

$registrationIDs = array($_POST['devices']);

このようなエラーを通知するには、 ini 値display_errorsを使用してデバッグ用のエラー ログまたは PHP エラー メッセージの出力を有効にする必要があります。log_errorserror_reporting


しかし、array($_POST['devices'])期待されていることさえしません。array(...)は、php の配列初期化構造です。($_POST['devices']) を別の配列にラップするだけです。

... の出力を見たいと思いますvar_dump($_POST);。これにより、さらに支援する機会が得られます..

于 2013-04-06T13:35:03.543 に答える