且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实现GCM时如何从android应用程序调用服务器应用程序servlet来注册设备

更新时间:2023-12-04 14:33:25

这是使用 HTTP GET 请求将注册 ID 发送到您的服务器的示例代码.我正在使用 org.apache.http.* 库的类.它假设您的服务器上有一个页面,该页面接受名为 regId 的参数中的注册 ID(在示例中,它是一个 jsp 页面,但它可以是 PHP在您的服务器中).您必须添加错误处理代码和解析服务器响应才能完成此示例.

Here's a sample code for sending the registration ID to your server using an HTTP GET request. I'm using classes of the org.apache.http.* library. It assumes you have a page on your server that accepts the registration ID in a parameter called regId (in the sample it's a jsp page, but it can be PHP of whatever you have in your server). You'll have to add error handling code and parsing of the server response in order to complete this sample.

  String responseString= null;

  try {
    URI url            = new URI ("http://your-server-domain/your-server-page.jsp?regId="+THE_REGISTRATION_ID);
    HttpGet httpGet    = new HttpGet (url);
    // defaultHttpClient
    HttpParams
      httpParameters   = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used. 
    int
      timeoutConnection= 3000;
    HttpConnectionParams.setConnectionTimeout (
      httpParameters,
      timeoutConnection
                         );

    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket  = 5000;
    HttpConnectionParams.setSoTimeout (
      httpParameters,
      timeoutSocket
                         );

    DefaultHttpClient
     httpClient        = new DefaultHttpClient (httpParameters);

    HttpResponse
      httpResponse     = httpClient.execute (httpGet);
    HttpEntity
      httpEntity       = httpResponse.getEntity ();

    if (httpResponse.getStatusLine().getStatusCode() != 200)
    {
      Log.e (
        _context.getString(R.string.app_name),
        "Server Call Failed : Got Status Code " + httpResponse.getStatusLine().getStatusCode() + " and ContentType " + httpEntity.getContentType().getValue()
                         );
      // add code to handle error
    }

    responseString     = EntityUtils.toString (httpEntity);
  } catch (UnsupportedEncodingException e) {
    Log.e(_context.getString(R.string.app_name),e.toString(),e);
    // add code to handle error
  } catch (ClientProtocolException e) {
    Log.e(_context.getString(R.string.app_name),e.toString(),e);
    // add code to handle error
  } catch (IOException e) {
    Log.e(_context.getString(R.string.app_name),e.toString(),e);
    // add code to handle error
  } catch (URISyntaxException e) {
    Log.e(_context.getString(R.string.app_name),e.toString(),e);
    // add code to handle error
  }