2015-03-27 2 views
0

Я использовал свой ключ для браузера, чтобы отправить сообщение серверу gcm. Также попробовал это с ключом сервера, но все равно получал такую ​​же ошибку. Я также попытался сделать аутентификацию, используя defaulthttpclient с именем пользователя и паролем, но не получил никакого результата.получение кода ответа 401 при отправке сообщения на сервер gcm с помощью ключа браузера

вот код моего сервера приложений:

package com.example.gcmserver; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.HttpException; 
import org.apache.http.HttpRequest; 
import org.apache.http.HttpRequestInterceptor; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.auth.AuthScope; 
import org.apache.http.auth.AuthState; 
import org.apache.http.auth.Credentials; 
import org.apache.http.auth.UsernamePasswordCredentials; 
import org.apache.http.client.CredentialsProvider; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.protocol.ClientContext; 
import org.apache.http.impl.auth.BasicScheme; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.protocol.HttpContext; 

public class Server { 
    public static void main(String[] args) throws IOException { 

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

     DefaultHttpClient client = new DefaultHttpClient(); 
     client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("username", "password")); 
     client.addRequestInterceptor(new HttpRequestInterceptor() { 


    @Override 
    public void process(HttpRequest arg0, HttpContext context) 
      throws HttpException, IOException { 
     // TODO Auto-generated method stub 
      AuthState state = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); 
      if (state.getAuthScheme() == null) { 
       BasicScheme scheme = new BasicScheme(); 
       CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); 
       Credentials credentials = credentialsProvider.getCredentials(AuthScope.ANY); 
       if (credentials == null) { 
        throw new HttpException(); 
       } 
       state.setAuthScope(AuthScope.ANY); 
       state.setAuthScheme(scheme); 
       state.setCredentials(credentials); 
    }} 
}, 0); 





     HttpPost post = new HttpPost(url); 


      HttpPost httppost = new HttpPost("https://android.googleapis.com/gcm/send"); 

      List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); 
      urlParameters.add(new BasicNameValuePair("data.registration id","APA91bGChJVdx2L1AUIJEVIBBVEkxEAk6zixj5V-L--fDGXudvrtl5gSQDgAP4iUJoMRq57sLSpGtsSQ5gnprX4McOPq7WxglKeQyTmaysVb0r-adOZ4tTjWG2MYwVEayFKy9Rwf1mloVt2jb-_izUdN-SfKvlpUpEYXNNT1987tYASKCcam16g")); 

      urlParameters.add(new BasicNameValuePair("data.title", "e-pass application")); 
      urlParameters.add(new BasicNameValuePair("data.message", "Your code is 13133")); 


      httppost.setHeader("Authorization", 
        "key=AIzaSyDANlJHGPmzo1so_yyqkYZO7LSrQpnR7mk"); 
      httppost.setHeader("Content-Type", 
        "application/x-www-form-urlencoded;charset=UTF-8"); 

      post.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8")); 

      HttpResponse response = client.execute(post); 
      System.out.println("Response Code : " 
         + response.getStatusLine().getStatusCode()); 

      BufferedReader rd = new BufferedReader(
        new InputStreamReader(response.getEntity().getContent())); 

      StringBuffer result = new StringBuffer(); 
      String line = ""; 
      while ((line = rd.readLine()) != null) { 
       result.append(line); 
      } 
} 
} 

I have also add the httpclient, httpcore jar files in build path but still getting error. 

ответ

0

Есть несколько возможных причин, которые там кода ответа 401, как ошибка в вашем проекте ID. Вы, возможно, забыли, что можно использовать службу облачных сообщений в консоли api.

Вы можете более подробно на here :)

0

пожарной код уведомления база Нажмите на Яве

private boolean sendFCMNotification(String fcmKey,JSONObject jsonDataObject){   
     try { 
      String serverKey = "AAAAZmvesa8:APA91bHdK"; 
      String url = "https://fcm.googleapis.com/fcm/send"; 
      HttpClient httpclient = HttpClients.createDefault(); 
      HttpPost httppost = new HttpPost(url); 
      JSONObject json = new JSONObject(); 
      json.put("to",fcmKey); 
      json.put("time_to_live",100); 
      //set data object 
      json.put("data",jsonDataObject); 
      StringEntity stringEntity = new StringEntity(json.toString()); 
      httppost.setEntity(stringEntity); 
      log.info("request string: "+json.toString()); 
      httppost.setHeader("Authorization","key="+serverKey); 
      httppost.setHeader("Content-Type","application/json"); 
      //Execute and get the response. 
      HttpResponse response = httpclient.execute(httppost); 
      HttpEntity entity = response.getEntity(); 
      if (entity != null) { 
       InputStream inputStream = entity.getContent(); 
       try { 
        // do something useful 
        String responseStr = streamToString(inputStream); 
        JSONObject responseObject = new JSONObject(responseStr); 
        if(responseObject.getInt("success")>0) { 
         log.info("notification sent successful: "); 
         return true; 
        }else{ 
         log.info("notification sent fail: "); 
         return false; 
        } 
       } finally { 
        inputStream.close(); 
       } 
      } 

     }catch(Exception e){ 
      log.info("msg: "+e.getMessage()); 
     } 
     return false; 
    } 

    private String streamToString(InputStream inputStream){ 
     ByteArrayOutputStream result = new ByteArrayOutputStream(); 
     String string = ""; 
     try { 
      byte[] buffer = new byte[1024]; 
      int length; 
      while ((length = inputStream.read(buffer)) != -1) { 
       result.write(buffer, 0, length); 
      } 
      string = result.toString("UTF-8"); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return string; 
    } 
Смежные вопросы