我正在尝试从 Android 开发者网站了解 GCM。我已经按照以下说明实现了客户端 Android 应用程序http://developer.android.com/google/gcm/client.html和 http 服务器应用程序(不是基于 XMPP 的服务器应用程序),遵循以下网址的说明http://developer.android.com/google/gcm/http.html。我使用的代码是从下载的https://code.google.com/p/gcm/正如他们所提到的。 GCM注册功能在我的手机上完美运行。
现在的问题是,我如何将手机的注册ID发送到我的http服务器应用程序。我知道我应该在 android 应用程序的 DemoActivity.java 文件中的 sendRegistrationIdToBackend() 中放置一些代码,以便简单地调用我的服务器应用程序上的 RegisterServlet。但我对 java 和 android 很陌生,只是不知道该怎么做。任何有关我如何编写这段代码的建议将不胜感激。
以下是使用 HTTP GET 请求将注册 ID 发送到服务器的示例代码。我正在使用的课程org.apache.http.*
图书馆。它假设您的服务器上有一个页面,该页面接受名为 regId 的参数中的注册 ID(在示例中,它是jsp
页面,但它可以是PHP
服务器中的任何内容)。您必须添加错误处理代码并解析服务器响应才能完成此示例。
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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)