Estoy tratando de enviar una solicitud al servidor Firebase para FCM y, como dice la documentación de FCM, debería ser una solicitud POST con datos JSON. Esta es la muestra.

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{ "data": {
    "score": "5x1",
    "time": "15:10"
  },
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}

Entonces, ¿alguien puede dar un código adecuado que envíe la solicitud POST con estos datos JSON?

Esto es lo que probé pero no funciona

AsyncT.java

package com.example.artin.pushnotifications;

import android.os.AsyncTask;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

class AsyncT extends AsyncTask<Void,Void,Void> {

    @Override
    protected Void doInBackground(Void... params) {

        try {
            URL url = new URL("https://fcm.googleapis.com/fcm/send"); //Enter URL here
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST"); // here you are telling that it is a POST request, which can be changed into "PUT", "GET", "DELETE" etc.
            httpURLConnection.setRequestProperty("Content-Type", "application/json"); // here you are setting the `Content-Type` for the data you are sending which is `application/json`
            httpURLConnection.setRequestProperty("Authorization","key=AIzaSyDZx9l_Izta9AjVS0CX70ou8OjbDVVGlHo");
            httpURLConnection.connect();

            JSONObject jsonObject = new JSONObject();
            JSONObject param = new JSONObject();
            param.put("Hii","there");

            jsonObject.put("data",param);
            jsonObject.put("to", "dXazhmeFSSU:APA91bG23o75zeNOCb7pY-OCQG4BsGbY-YZrSnDrvLWv1");

            DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
            wr.writeBytes(jsonObject.toString());
            wr.flush();
            wr.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }


}

Y lo ejecuto cuando se presiona el botón

AsyncT asyncT = new AsyncT();
asyncT.execute();
3
Aram Sheroyan 21 ago. 2016 a las 23:48

2 respuestas

La mejor respuesta

Usé OkHttp y ahora funciona. Aquí está el código si alguien lo necesita.

Primero agregue OkHttp en aplicaciones graddle.build

compile 'com.squareup.okhttp3:okhttp:3.4.1'

Aquí está el método para enviar la solicitud POST Json

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    OkHttpClient client = new OkHttpClient();

    Call post(String url, String json, Callback callback) {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .addHeader("Content-Type","application/json")
                .addHeader("Authorization","key=YourApiKey")
                .url(url)
                .post(body)
                .build();
        Call call = client.newCall(request);
        call.enqueue(callback);
        return call;
    }

Y simplemente cree el objeto Json y llámelo donde desee.

try {
    JSONObject jsonObject = new JSONObject();
    JSONObject param = new JSONObject();
    param.put("Hii", "there");
    param.put("Hours", "12:50");
    jsonObject.put("data", param);
    jsonObject.put("to", "TokenOfTheDevice");
    post("https://fcm.googleapis.com/fcm/send", jsonObject.toString(), new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //Something went wrong
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String responseStr = response.body().string();
                        Log.d("Response", responseStr);
                        // Do what you want to do with the response.
                    } else {
                        // Request not successful
                    }
                }
            }
    );
} catch (JSONException ex) {
    Log.d("Exception", "JSON exception", ex);
}
4
Zeeshan Ali 27 feb. 2017 a las 01:24

Esto se puede hacer usando AsyncTask, HTTPRequest

    private class PostTask extends AsyncTask<String, String, String> {

      String Url = "//fcm.googleapis.com/fcm/send"

      @Override
      protected String doInBackground(String... data) {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(Url);

        try {
          //add data
          List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
          nameValuePairs.add(new BasicNameValuePair("data", data[0]));
          httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
          //execute http post
          HttpResponse response = httpclient.execute(httppost);

        } catch (ClientProtocolException e) {

        } catch (IOException e) {

        }
      }
    }

Esto se puede llamar usando new PostTask().execute();

1
Adrian Pottinger 21 ago. 2016 a las 20:56