下面是使用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
}
工作正常!因爲我在Web服務器上使用servlet來處理註冊請求,所以我在HTTP GET請求中使用'URI url = new URI(「http:// server-domain/register?regId =」+ THE_REGISTRATION_ID);''。並確保在我的服務器應用程序的web中有 RegisterServlet servlet-name> /register url-pattern> servlet-mapping> .xml文件。 –
faizal
你是如何實現你的http服務器以便它接受註冊ID的? – 2014-06-03 15:41:14
@ user2320244在這裏回答太長了。你應該首先選擇你希望實現你的服務器的語言(Java Servlet,JSP,PHP,.NET等)。 – Eran