尝试将JSON数据发布到Android设备时出错

时间:2015-03-09 21:07:56

标签: java android json google-cloud-messaging

我已经按照教程here尝试将数据发送到Android设备。我已经将我的Java类缩减为:

public class App {
    public static void main( String[] args ) {

        try {                   
            String apiKey = "api key generated in Google Developer Console...";
            String deviceId = "Device Id generated, retrieved directly from logcat, as per tutorial...";
            Content content = new Content();

            content.addRegId(deviceId);
            content.createData("Title", "Notification Message");
            URL url = new URL("https://android.googleapis.com/gcm/send");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Authorization", "key=" + apiKey);
            conn.setDoOutput(true);
            ObjectMapper mapper = new ObjectMapper();

            mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            mapper.writeValue(wr, content);
            wr.flush();
            wr.close();
            int responseCode = conn.getResponseCode();
            System.out.println(responseCode == 200 ? responseCode + ". This is the response we want..." : responseCode + ". This is not the response we want...");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            System.out.println(response.toString());
        } catch (MalformedURLException mue) {
            mue.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

这是我的Content类:

public class Content implements Serializable{

    private List<String> registration_ids;
    private Map<String,String> data;

    public void addRegId(String regId) {
        if(registration_ids == null)
            registration_ids = new LinkedList<String>();
        registration_ids.add(regId);        
    }

    public void createData(String title, String message) {
        if (data == null) 
            data = new HashMap<String,String>();

        data.put("title", title);
        data.put("message",  message);
    }

}

我收到400响应代码

java.io.IOException: Server returned HTTP response code: 400 for URL: https://android.googleapis.com/gcm/send

我确定我错过了一些小东西,但我看不出它在哪里。

0 个答案:

没有答案