【问题标题】:How can I send more than one String through a POST or JSON? Can I send a JSON array through another JSON object?如何通过 POST 或 JSON 发送多个字符串?我可以通过另一个 JSON 对象发送 JSON 数组吗?
【发布时间】:2014-06-30 14:40:17
【问题描述】:

我正在尝试为 android 实现推送通知。我想向多个电话发送相同的消息。目前它可以发送到一部手机。我想从一个 mysql 数据库中获取注册密钥并向所有这些手机发送一条消息。

问题是我对 json 和数组以及 POST 感到困惑。我可以通过另一个 JSON 对象发送 JSON 数组吗?如何输入params.add(new BasicNameValuePair("regId", regkeys)); 多个注册码?我试图使 regkeys 成为一个数组,但它没有用。我知道它必须以某种形式出现

{ "message":"some message here", "regIds": [ "dsdfsfet366767547", "63567356366reygh", "sgdgtwetwetsdgsdg", "sdgsdgsdgwet24t" ] }

但我不知道如何创建它。

php代码

     $regId = $_POST["regId"];
     $message = $_POST["message"];
...
$registatoin_ids = array($regId);
    $message = array("price" => $message);
     $result = $gcm->send_notification($registatoin_ids, $message);
...
     public function send_notification($registatoin_ids, $message) {...}

安卓代码

 String regkeys = regkey.getText().toString();
 String message = messg.getText().toString();

...

List<NameValuePair> params = new ArrayList<NameValuePair> ();
params.add(new BasicNameValuePair("regId", regkeys));
params.add(new BasicNameValuePair("message", message));

JSONObject json = parser2.makeHttpRequest(url, params); 

...

 public class jParser2 {

static InputStream is = null;
static JSONObject jObject = null;
static String json = "";

public jParser2(){

}

public JSONObject makeHttpRequest(String url, List<NameValuePair> params){

try {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);

    httpPost.setEntity(new UrlEncodedFormEntity(params));

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();

} catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
try {
    BufferedReader reader = new BufferedReader (new InputStreamReader (is, "iso-8859-1"), 8);

    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine())!=null){
        sb.append(line+"\n");
    }
    is.close();
    json = sb.toString();
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();        
}   
try {
        jObject = new JSONObject(json);
} catch (JSONException e) {
        // TODO Auto-generated catch block
    e.printStackTrace();
}   

    return jObject;
}
  }

我的服务器到 GCM 代码。

public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';

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

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

    $headers = array(
        'Authorization: key=' . GOOGLE_API_KEY,
        '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);

    // Disabling SSL Certificate support temporarly
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

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

    // Execute post
    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('Curl failed: ' . curl_error($ch));
    }

    // Close connection
    curl_close($ch);
    echo $result;
}

【问题讨论】:

  • 目前还不清楚您要在 Android 代码中执行什么操作。我假设 PHP 代码用于从服务器发送 GCM 消息。从 Android 代码发送的 HTTP 请求的目的是什么?它发送到您的服务器吗?到 GCM 服务器?
  • android代码只是将消息从手机发送到服务器,服务器发送到多个其他手机。
  • Android代码是否也将消息的收件人注册ID发送到服务器?通常注册ID存储在服务器中。
  • 是的,目前我只是在测试它,所以我是从 android 手动发送注册 ID。之后的想法是只做一个 mysql 查询从服务器获取注册密钥,然后将它们从 android 发送回服务器,然后与消息一起发送到 GCM。

标签: php android json push-notification google-cloud-messaging


【解决方案1】:

我不知道你的 $gcm-&gt;send_notification 函数是什么样子的,但它应该是这样的:

$data = array( 'message' => 'some message' );
$ids = array( 'reg-id1', 'reg-id2' );
$payload = array(
                'registration_ids'  => $ids,
                'data'              => $data,
                );
$headers = array( 
                    'Authorization: key=' . $apiKey,
                    'Content-Type: application/json'
                );

请注意,为了向多个注册 ID 发送相同的消息,请求的内容类型必须是 JSON。注册 ID 在包含数组的 registration_ids 参数中发送,通知数据在包含字典的 data 参数中。

【讨论】:

  • 我在原始帖子中添加了$gcm-&gt;send_notification。我在该代码中使用CURL。我是否必须重写整个 php 文件才能发送到多个设备?
  • @Jerome 不,您的 $gcm-&gt;send_notification 已经正确处理发送到多个注册 ID。
【解决方案2】:

是的,您可以将带有 regIds 的数组放入 JSON 对象中,并将 JSON 对象放入 Post 中:

List<NameValuePair> params = new ArrayList<NameValuePair> ();
params.add(new BasicNameValuePair("json", JsonObject));
httpPost.setEntity(new UrlEncodedFormEntity(params));

希望对你有所帮助。

【讨论】:

    【解决方案3】:

    我建议使用GSON

    现在,要使用,创建一个类:

    Class Messages {
        public String message;
        public ArrayList<String> regIDs;
    
        public void setMessage(String message) {
            this.message = message;
        }
    
        public ArrayList<String> getRegIDs() {
            return regIDs;
        }    
    }
    

    现在当你想向服务器发送一些数据时,创建这个类的一个新对象。

    Messages messages = new Messages();
    messages.setMessage("Some message here");
    //Add all the regn IDs to the regIDs List. 
    ArrayList<String> regIDs = messages.getRegIDs()
    regIDs.add("regnID1");
    regIDs.add("regnID2");
    regIDs.add("regnID3");
    regIDs.add("regnID4");
    
    //Add as many IDs as you want. 
    //then create a new GSON Object. 
    
    Gson gson = new Gson();
    String jsonString = gson.toJSON(messages);
    

    现在jsonString 将自动包含您指定格式的 JSON 字符串。因此,使用 jsonString 变量的内容向您的服务器发送一个 POST 请求。然后在php端,使用json_decode解码成数组,遍历regIDs数组发送多条gcm消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-11
      • 2014-05-20
      • 2012-02-17
      • 1970-01-01
      • 1970-01-01
      • 2011-10-02
      • 2011-10-01
      • 2012-10-27
      相关资源
      最近更新 更多