当我运行 GCM 客户端代码时,出现“invalidRegistration”错误。我检查了引用的页面。但仍然无法成功 1.JSON文件提供的API密钥和我在配置过程不同时得到的服务器API密钥。但对于两者本身,我都得到了InvalidRegistarion。`public class MainActivity 扩展 AppCompatActivity {
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.textView);
new GCMRequest().execute();
}
private class GCMRequest extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... voids) {
final String API_KEY = "AIzaSyCNPlrqXeZ8IlNYsQGlseHhHPCfgcR5V7c"; // An API key saved on the app server that gives the app server authorized access to Google services
final String CLIENT_REG_ID = "821083769456"; //An ID issued by the GCM connection servers to the client app that allows it to receive messages
final String postData = "{ \"registration_ids\": [ \"" + CLIENT_REG_ID + "\" ], " +
"\"delay_while_idle\": true, " +
"\"data\": {\"tickerText\":\"My Ticket\", " +
"\"contentTitle\":\"My Title\", " +
"\"message\": \"Test GCM message from GCMServer-Android\"}}";
try {
URL url = new URL("https://android.googleapis.com/gcm/send");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", "key=" + API_KEY);
OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
writer.write(postData);
writer.flush();
writer.close();
outputStream.close();
int responseCode = urlConnection.getResponseCode();
InputStream inputStream;
if (responseCode < HttpURLConnection.HTTP_BAD_REQUEST) {
inputStream = urlConnection.getInputStream();
} else {
inputStream = urlConnection.getErrorStream();
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String temp, response = "";
while ((temp = bufferedReader.readLine()) != null) {
response += temp;
}
return response;
} catch (IOException e) {
e.printStackTrace();
return e.toString();
}
}
@Override
protected void onPostExecute(String message) {
super.onPostExecute(message);
if (mTextView != null) {
try {
JSONObject jsonObject = new JSONObject(message);
mTextView.setText(jsonObject.toString(5));
} catch (JSONException e) {
e.printStackTrace();
mTextView.setText(e.toString());
}
}
}
}
}`
输出是:
{
multicast_id:XXXX,
success:0,
failure:1,
results:
{
error:InvalidRegistration
}
提前致谢。