2012-02-04 51 views
0

我已经参考了Vogella Tutorial for Android C2DM 并实现了如下客户端和服务器。Android C2DM无法链接客户端和服务器

我已经在应用程序中使用了3个URL,在客户端使用了1个,在服务器中使用了2个。

代替第一个URL,应该有我创建的服务器地址。但我不明白到底放哪儿。

2个URL(谷歌的子网址)的其余部分无法正确访问。

我已经包围他们强调了这些3网址的使用与

//==========================================================================

和编号他们。

请注意,我可以在客户端注册但无法收到任何消息。

而在服务器端,我得到身份验证,但当我尝试发送消息时,它给出UnknownHostException

我知道我在这个问题上还不太清楚,但我绝对是初学者,当涉及到Android C2DM development

任何帮助表示赞赏。

建议更改(如果有)。

客户端的代码片段(C2DMRegistrationReceiver.java)

public void sendRegistrationIdToServer(String deviceId, 
     String registrationId) { 
    Log.d("C2DM", "Sending registration ID to my application server"); 
    HttpClient client = new DefaultHttpClient(); 
    HttpPost post; 

    // 1.) ======================================================================== 
post = new HttpPost("http://vogellac2dm.appspot.com/register"); 
    //============================================================================= 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
     // Get the deviceID 
     nameValuePairs.add(new BasicNameValuePair("deviceid", deviceId)); 
     nameValuePairs.add(new BasicNameValuePair("registrationid", 
       registrationId)); 

     post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     HttpResponse response = client.execute(post); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(
       response.getEntity().getContent())); 
} 

服务器的代码片段

public class ServerSimulator extends Activity { 
    private SharedPreferences prefManager; 
    private final static String AUTH = "authentication"; 
    private static final String UPDATE_CLIENT_AUTH = "Update-Client-Auth"; 
    public static final String PARAM_REGISTRATION_ID = "registration_id"; 
    public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle"; 
    public static final String PARAM_COLLAPSE_KEY = "collapse_key"; 
    private static final String UTF8 = "UTF-8"; 

    // Registration is currently hardcoded 
    private final static String YOUR_REGISTRATION_STRING = "APA91bFQut1tqA-nIL1ZaV0emnp4Rb0smwCkrMHcoYRXeYVtIebJgrzOHQj0h76qKRzd3bC_JO37uJ0NgTcFO87HS9V7YC-yOP774pm0toppTHFO7Zc_PAw"; 

    private SharedPreferences prefs; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     prefManager = PreferenceManager.getDefaultSharedPreferences(this); 
    } 

    public void getAuthentification(View view) { 
     SharedPreferences prefs = PreferenceManager 
       .getDefaultSharedPreferences(this); 

     HttpClient client = new DefaultHttpClient(); 
    // 2.) ========================================================================== 
     HttpPost post = new HttpPost(
       "https://www.google.com/accounts/ClientLogin"); 
    //============================================================================== 

     try { 

      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
      nameValuePairs.add(new BasicNameValuePair("Email", prefs.getString(
        "user", "[email protected]"))); 
      nameValuePairs.add(new BasicNameValuePair("Passwd", prefs 
        .getString("password", "myPassword"))); 
      nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE")); 
      nameValuePairs.add(new BasicNameValuePair("source", 
        "Google-cURL-Example")); 
      nameValuePairs.add(new BasicNameValuePair("service", "ac2dm")); 

      post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      HttpResponse response = client.execute(post); 
      BufferedReader rd = new BufferedReader(new InputStreamReader(
        response.getEntity().getContent())); 

      String line = ""; 
      while ((line = rd.readLine()) != null) { 
       Log.e("HttpResponse", line); 
       if (line.startsWith("Auth=")) { 
        Editor edit = prefManager.edit(); 
        edit.putString(AUTH, line.substring(5)); 
        edit.commit(); 
        String s = prefManager.getString(AUTH, "n/a"); 
        Toast.makeText(this, s, Toast.LENGTH_LONG).show(); 
       } 

      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    public void sendMessage(View view) { 
     try { 
      Log.e("sendMessage", "Started"); 
      String auth_key = prefManager.getString(AUTH, "n/a"); 
      // Send a sync message to this Android device. 
      StringBuilder postDataBuilder = new StringBuilder(); 
      postDataBuilder.append(PARAM_REGISTRATION_ID).append("=") 
        .append(YOUR_REGISTRATION_STRING); 

      postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY).append("=") 
        .append("0"); 

      postDataBuilder.append("&").append("data.payload").append("=") 
        .append(URLEncoder.encode("Lars war hier", UTF8)); 

      byte[] postData = postDataBuilder.toString().getBytes(UTF8); 

      // Hit the dm URL. 
    // 3.) ========================================================================== 
      URL url = new URL("https://android.clients.google.com/c2dm/send"); 
    //=============================================================================== 

      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.setDoOutput(true); 
      conn.setUseCaches(false); 
      conn.setRequestMethod("POST"); 
      conn.setRequestProperty("Content-Type", 
        "application/x-www-form-urlencoded;charset=UTF-8"); 
      conn.setRequestProperty("Content-Length", 
        Integer.toString(postData.length)); 
      conn.setRequestProperty("Authorization", "GoogleLogin auth=" 
        + auth_key); 

      OutputStream out = conn.getOutputStream(); 
      out.write(postData); 
      out.close(); 

      int responseCode = conn.getResponseCode(); 

      Log.e("Response Code=", String.valueOf(responseCode)); 
      // Validate the response code 
      // Check for updated token header 
      String updatedAuthToken = conn.getHeaderField(UPDATE_CLIENT_AUTH); 
      if (updatedAuthToken != null && !auth_key.equals(updatedAuthToken)) { 
       Log.i("C2DM", 
         "Got updated auth token from datamessaging servers: " 
           + updatedAuthToken); 
       Editor edit = prefManager.edit(); 
       edit.putString(AUTH, updatedAuthToken); 
      } 

      String responseLine = new BufferedReader(new InputStreamReader(
        conn.getInputStream())).readLine(); 

      String[] responseParts = responseLine.split("=", 2); 
      if (responseParts.length != 2) { 
       Log.e("C2DM", "Invalid message from google: " + responseCode 
         + " " + responseLine); 
       throw new IOException("Invalid response from Google " 
         + responseCode + " " + responseLine); 
      } 

      if (responseParts[0].equals("id")) { 
       Log.i("Tag", "Successfully sent data message to device: " 
         + responseLine); 
      } 

      if (responseParts[0].equals("Error")) { 
       String err = responseParts[1]; 
       Log.w("C2DM", 
         "Got error response from Google datamessaging endpoint: " 
           + err); 
       // No retry. 
       throw new IOException(err); 
      } 
     } catch (Exception e) { 
      throw new RuntimeException(e); 
     } 
    } 
} 

回答

1

对于URL 1,你需要的地方在服务器上实现某种形式的数据存储的那可以接收注册手机的请求并存储他们的注册ID,以便您稍后可以向他们发送c2dm通知。就我而言,我使用了一个接受xml over apache的apache2服务器。

对于URL 2,它听起来像你已经得到了工作,因为你说“而在服务器端,我得到了认证”。你到底在这里寻找什么?

对于URL 3,您应该使用https://android.apis.google.com/c2dm/send根据the google c2dm docs。虽然您使用的地址为我解决。请注意,谷歌ssl证书用于上述URL是错误的,并不会正确验证,所以你可能会遇到,如果你想安全地发送通知。测试时,您的模拟器/手机是否可以访问互联网?我不知道为什么你会得到该URL的UnknownHost例外。

+0

对于URL 1,我创建了服务器。我只是不知道如何链接客户端和服务器。 – GAMA 2012-02-06 05:37:31

+0

URL 2 - 正在工作。 – GAMA 2012-02-06 05:37:57

+0

URL 3 - 按照您指定的方式尝试了上面的URL,它给出'请求时间失败:java.net.SocketException:地址族不受协议支持......可能是什么问题? – GAMA 2012-02-06 05:41:01

相关问题