下面是使用 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
}