我正在尝试为GCM通信实现HTTP服务器。提供正确的密钥后,我将HTTP响应代码设置为“400”。以下是代码段:
URL url = new URL("https://android.googleapis.com/gcm/send");
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.sgp.com", 8080));
HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key="+"AIzaSyAYc53L6kg_XerwoWdLjUAi2iEfNKidSF8");
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeUTF("{\"collapse_key\" : \"Food-Promo\", \"data\" : {\"Category\" : \"FOOD\",\"Type\": \"VEG\",}, \"registration_ids\": [\"APA91bEk7GPFVxzOidvB3JKCMWq3FHpAaTj2dBv9VGOQkKtLAEiVGR8TDi1fsU4D1k293ODAFTJ8dNfE2gzJNfCvB1sjewZu2fGOIJmY8dgjcNTZQYi4QfyQH-AaO0qEmQnbEeEtsUQ5LzWrIHboAhJMx1bfdsO9bg\"]}");
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
有人可以帮忙吗?
答案 0 :(得分:3)
仅在以下情况下出现400错误:
仅适用于JSON请求。 Indicates that the request could not be parsed as JSON
,或者它包含无效字段(例如,传递一个预期数字的字符串)。在响应中描述了确切的失败原因,并且在重试请求之前应该解决问题。
Reference
所以你可以尝试这个代码,它为我工作
为GCM的标准邮件格式创建一个POJO类
public class Content implements Serializable {
public List<String> registration_ids;
public 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);
}
}
请求GCM向Android设备发送通知消息的代码,
String apiKey = ""; //API key provided by Google Console
String deviceID="";//Device Id
Content content = new Content();
//POJO class as above for standard message format
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();
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
mapper.writeValue(wr, content);
wr.flush();
wr.close();
responseCode = conn.getResponseCode();
希望这可以帮助您解决问题... !!!!!