如何使用httpurlconnection为GCM发布json

时间:2016-05-24 04:24:46

标签: android json google-cloud-messaging

我有一个使用GCM(Google云消息传递)的应用。 现在,当我想发送下游消息时,我正在使用带有作曲家的软件(Postman / fidller)。

我想知道的是,如何从其他Android应用程序发送这个Json,我很难找到使用httpurlconnection的正确语法。 这是我的代码:

                URL myURL = new URL("https://gcm-http.googleapis.com/gcm/send");
                HttpURLConnection myURLConnection = (HttpURLConnection) myURL.openConnection();
                String basicAuth = "key " + "=AIzaXXXXXXXXXXXXXXXXXXX";
                myURLConnection.setRequestProperty("Authorization", basicAuth);
                myURLConnection.setRequestProperty("Content-Type", "application/json");
                myURLConnection.setRequestMethod("POST");
                myURLConnection.setUseCaches(false);
                myURLConnection.setDoInput(true);
                myURLConnection.setDoOutput(true);


                DataOutputStream wr = new DataOutputStream(myURLConnection.getOutputStream());
                JSONObject jsonParam = new JSONObject();
                jsonParam.put("registration_ids", "XXXXXXXXXXXXXXXXXXXXXXXXXXX");
                jsonParam.put("message", "hello gcm!");
                wr.writeBytes(jsonParam.toString());
                wr.flush();
                wr.close();

以下是我需要发送的参数:

{       
  "registration_ids":["XXXXXXXXXXXXXXXXXXXXXXXXX"],
  "data": {
    "Hello" : "World",
    "message": "Hello"
  } 
}

标题是:

 Content-Type:  application/json
 Authorization: key=AIzaXXXXXXXXXXXXXXXXXXX

谢谢。

1 个答案:

答案 0 :(得分:0)

我将为您提供使用PHP和My SQL数据库从Android应用程序向服务器发送数据的一般示例。

1-创建数据库并将其命名为 derar 或任何您想要的名称。

2-在该数据库中创建一个表,并将其命名为 movie ,如下所示

CREATE TABLE IF NOT EXISTS `movie` (
  `movie_id` int(11) NOT NULL AUTO_INCREMENT,
  `movie_name` varchar(200) NOT NULL,
  PRIMARY KEY (`movie_id`)
)

3-转到“我的电脑”,打开wamp文件夹,然后打开www文件夹。

4-创建一个新文件夹并使用 derar

命名

5-在该文件夹中创建两个这样的php文件:

<强>的config.php

<?php
$servername="localhost";
$username="root";
$password="";
$db="derar";// or the name of your database
?>

<强> insertDataToServer.php

<?php 
require ('config.php');
$connection=mysqli_connect($servername,$username,$password,$db);
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$movie_name=$obj['movie_name'];
mysqli_query($connection,"insert into  movie (movie_id, movie_name) VALUES (NULL,'$movie_name');");
echo "inserted";
?>

此PHP脚本没有安全性(SQL注入)

6-创建一个新的Android应用程序。

7- MainActivity

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    private  Button send_button;
    private String Server_URL="http://192.168.1.105/derar/insertDataToServer.php";//change the 192.168.1.105 with your computer ip address 
    private String movie_name="Titanic";// data that you want to send to server. It can be taken from EditText and ..etc
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        send_button=(Button)findViewById(R.id.send_button);// Button Assignment
        send_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SendDataToServer sendDataToServer=new SendDataToServer();
                sendDataToServer.execute(Server_URL,movie_name);


            }
        });// Button On Click Listener
    }


    private class SendDataToServer extends AsyncTask<String, Void, Boolean> {

        @Override
        protected Boolean doInBackground(String... urls) {

            OutputStream os = null;
            InputStream is = null;
            HttpURLConnection conn = null;


            try {

                URL url = new URL(urls[0]);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("movie_name", urls[1]);
                String message = jsonObject.toString();
                Log.d(message, "Test");
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setFixedLengthStreamingMode(message.getBytes().length);
                conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
                conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");

                conn.connect();

                os = new BufferedOutputStream(conn.getOutputStream());
                os.write(message.getBytes());

                os.flush();

                is = conn.getInputStream();


            } catch (MalformedURLException e) {
                Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                ;
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                ;
                e.printStackTrace();
                return false;
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {

                try {
                    assert os != null;
                    os.close();
                    assert is != null;
                    is.close();

                } catch (IOException e) {

                    e.printStackTrace();
                }

                conn.disconnect();
            }


            return true;
        }


        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {


                  Toast.makeText(getApplicationContext(), "Data has Been Sent Successfully ", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), "Error in sending Data", Toast.LENGTH_LONG).show();

            }

        }
    }
}

8- activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.win7.derar.MainActivity">

   <Button
       android:id="@+id/send_button"
       android:layout_width="match_parent"
       android:text="Press Here To Send Data To Server"
       android:layout_height="wrap_content" />
</RelativeLayout>

最后不要忘记将此权限添加到清单文件     的

我已经测试了这段代码,但它运行正常。