Java 中的 GCM 客户端无法正常工作

GCM Client in Java not working

我想创建一个 android GCM 发件人,它将 URL 发送到 Android 应用程序。我已经使用 this windows application 测试了我的 android 应用程序,它正在运行。我检查了C#中的代码并尝试将其转换为Java。但我什么也没得到。让我知道我错过了什么。

import java.util.*;
import java.util.logging.Logger;
import java.io.*;
import java.net.*;
import java.net.ProtocolException;

//import org.apache.http.HttpResponse;
import org.apache.http.*;
import org.apache.http.util.EntityUtils;


public class Client {

    String device_id;
    String api_id;
    String Msg;
    String ResultJSON;

    private String GCM_URI = "https://android.googleapis.com/gcm/send";

    HttpURLConnection gcmRequest = null;
    HttpResponse gcmResponse = null;

    Client()
    {
        //default constructor...do nothing
    }

    Client(String dev, String auth)
    {
        this.device_id = dev;
        this.api_id = auth;

    }

    public String Send(String message) throws IOException
    {
        // Escape condition
        if (device_id == null || api_id == null)
        {
            return "[ERROR] Device Token or API Key has not been set";
        }

        InitGCMClient();
        PostPayload(message);

        /*gcmResponse = (HttpResponse) gcmRequest.getResponseMessage();
        catch (WebException we)
        {
            return "[ERROR] There is a problem within processing GCM message \n" + we.Message;
        }*/

        try {
            System.out.println(gcmRequest);
            ResultJSON = gcmRequest.getResponseMessage();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ResultJSON;
    }

    public String ReadResponse(HttpResponse response)
    {
        //StreamReader responseReader = new StreamReader(response.GetResponseStream());
        //return responseReader.ReadToEnd();

        try {
            String responseString = EntityUtils.toString(response.getEntity());
            return responseString;
        } catch (ParseException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    private void InitGCMClient()
    {

        URL obj = null;
        try {
            obj = new URL(GCM_URI);
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            gcmRequest = (HttpURLConnection) obj.openConnection();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        gcmRequest.setRequestProperty("Content-Type", "application/json");
        gcmRequest.setRequestProperty("User-Agent", "Android GCM Message Sender Client 1.0");
        gcmRequest.setRequestProperty("Authorization", "key=" + api_id);

        try {
            gcmRequest.setRequestMethod("POST");
        } catch (ProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void PostPayload(String message) throws IOException
    {
        String payloadString = AssembleJSONPayload(device_id, message);        
        byte[] payloadByte = payloadString.getBytes("UTF-8");

        //gcmRequest.ContentLength = payloadByte.length;
        String len = new String(payloadByte);
        gcmRequest.setRequestProperty("Content-Length", len);

        gcmRequest.setDoOutput(true);
        gcmRequest.setDoInput(true);

        OutputStream payloadStream = gcmRequest.getOutputStream();

        payloadStream.write(payloadByte, 0, payloadByte.length);
        payloadStream.close();

    }

    public String AssembleJSONPayload(String gcmDeviceToken, String gcmBody)
    {
        String payloadFormatJSON =
            "{{" +
                "\"registration_ids\" : [\"" + gcmDeviceToken + "\"]," +
                "\"data\" : {{" +
                    " " + gcmBody + " " +
                "}}" +
            "}}";

        String payload = String.format(payloadFormatJSON, gcmDeviceToken, gcmBody);
        //Debug.WriteLine("payload : " + payload);
        System.err.println("payload : " + payload);
        return payload;
    }


    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        String dev = "<device_ID>";
        String auth = "<api_ID>";
        Client  cl = new Client(dev, auth);

        @SuppressWarnings("resource")
        Scanner sc = new Scanner(System.in);
        while(true)
        {

            System.out.println("\nSend your msg\n");
            String msg = sc.nextLine();
            cl.Send(msg);
        }
    }
}

我刚开始 Android。如果有任何相关建议,请告诉我。

输入:

"key":“http://upload.wikimedia.org/wikipedia/commons/2/23/Lake_mapourika_NZ.jpeg

在控制台中,我得到:

有效载荷:{{"registration_ids":["device_id"],"data":{{ "key":“http://upload.wikimedia.org/wikipedia/commons/2/23/Lake_mapourika_NZ.jpeg”}}}}

编辑

您在 AssembleJSONPayload 中的有效负载消息格式不正确。请使用以下代码构建负载:

String payloadFormatJSON =
        "{" +
                "\"registration_ids\" : [\"" + gcmDeviceToken + "\"]," +
                "\"data\" : {" +
                " " + gcmBody + " " +
                "}" +
                "}";

输出应该是:

payload : {"registration_ids" : ["gcmDeviceToken value"],"data" : {"gcmBody value"}}