为什么我不能将json字符串发送到谷歌gsm推送通知服务器?

时间:2015-10-14 08:31:46

标签: php android asp.net json

我是android的初学者,在android studio上编写简单的推送通知应用程序,用PHP编写服务器端应用程序,每件事都可以,应用程序工作正常,但我想将PHP应用程序更改为asp.net,但是现在我得到了错误的请求错误,我认为我的json字符串是错误的,在php json中定义了这一行:

   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) {
    print("");
        die('Curl failed: ' . curl_error($ch));

    }


并在asp.net中编写此代码:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
            httpWebRequest.ContentType = "application/json";
            //httpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
            httpWebRequest.Method = "POST";
            httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
            httpWebRequest.Headers.Add(string.Format("Sender: key={0}", SENDER_ID));

string json = "{\"registration_ids\":[\"" + regId + "\"]," + "\"data\": { \"message\" : \"1234\", \"name\": \"Arvind Sharma\"}}";
                Console.WriteLine(json);
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();

                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();


但现在我得到null结果,在android代码中写下这一行:

private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {


            String newMessage = intent.getExtras().getString(message);


会发生什么?为什么我得到空值?感谢您的帮助。

0 个答案:

没有答案