问题描述
我在Android的新的。我需要从我的应用程序调用REST风格的Web服务。
我可以从Android电子服务调用REST风格的Web服务?如果是的话那么它是如何实现?
I am new in android. I need to call RestFull web services from my app.Can i call RestFull web services from android service? if yes then how it implement?
推荐答案
在Android的直接通过HTTP方法Web服务消费导致ANR(Android版没有响应)异常和网络的主线程例外。因此,你将不得不使用的AsyncTask调用/使用Web服务。
Consuming Webservices directly via HTTP method in android causes ANR (Android not responding) exception and Network On Main Thread exception. Hence you would have to use an ASYNCTASK to call /consume web-services.
权限要求:
<uses-permission android:name="android.permission.INTERNET" />
code片断:
这是在Android客户端的主要活动。从这里,网络服务将在某些特定触发被消耗,说用户点击一个按钮。
使用调用后台的Web服务
This is the main activity in the android client. From here, the web-service would be consumed on some particular trigger, say user clicks a button.Use an AsyncTask for calling the web-service in background
class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
// Event that triggers the webservice call
new AsyncTaskOperation().execute();
}
/* Async Task called to avoid Android Network On Main Thread Exception. Web services need to be consumed only in background. */
private class AsyncTaskOperation extends AsyncTask <String, Void, Void>
{
private JSONObject json = null;
private ProgressDialog Dialog = new ProgressDialog(MenuActivity.this);
private boolean errorFlag = false;
protected void onPreExecute() {
Dialog.setMessage("Calling WebService. Please wait.. ");
Dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
Dialog.setInverseBackgroundForced(false);
Dialog.setCancelable(false);
Dialog.show();
}
@Override
protected Void doInBackground(String... paramsObj)
{
// Calling webservice to check if location reached.
json = RestClientServicesObject.callWebService(params);
if (json == null)
{
// Network error/Server error. No response from web-service.
errorFlag = true;
}
else
{
try
{
// Do action with server response
} catch (JSONException e)
{
e.printStackTrace();
}
} // End of if response obtained from web-service.
return null;
}
protected void onPostExecute(Void unused)
{
Dialog.dismiss();
if (errorFlag)
{
// No response from server
new AlertDialogDisplay().showAlertInfo (MainActivity.this, "Server Error", "Network / Server Error. Please try after sometime.");
}
else
{
// Perform activities based on server response
}// End of if response obtained from server
}// End of method onPostExecute
} // End of class AsyncTask
}// End of class Main Activity.
这是HttpClient的code为Web服务消费(POST请求)
This is the HTTPClient code for WebServices Consuming (POST REQUEST)
public class RestClientServices {
/* Call Web Service and Get Response */
private HttpResponse getWebServiceResponse(String URL, ArrayList <NameValuePair> params)
{
HttpResponse httpResponse = null;
try
{
HttpParams httpParameters = new BasicHttpParams();
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(URL);
try
{
httpPost.setEntity(new UrlEncodedFormEntity(params));
} catch (UnsupportedEncodingException e) {
}
httpResponse = httpClient.execute(httpPost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return httpResponse;
}
/* Get the Web Service response as a JSON Object */
private JSONObject responseToJSON (HttpResponse httpResponse)
{
InputStream is = null;
String json = "";
JSONObject jObj = null;
HttpEntity httpEntity = null;
try
{
if (httpResponse != null)
{
httpEntity = httpResponse.getEntity();
try {
is = httpEntity.getContent();
} catch (IllegalStateException e1) {
Log.v("a", "Error while calling web services " +e1);
e1.printStackTrace();
} catch (IOException e1) {
Log.v("a", "Error while calling web services " +e1);
e1.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
// Closing the input stream will trigger connection release
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("a", "Buffer Error. Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
Log.v("a", "JSON Object is " +jObj);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
}
}
catch (Exception e)
{
Log.e("a", "Error while calling web services " +e);
}
finally
{
// Release the response
try {
if (httpEntity != null)
{
httpEntity.consumeContent();
}
//httpResponse.getEntity().getContent().close();
} catch (IllegalStateException e) {
Log.e("a", "Error while calling web services " +e);
e.printStackTrace();
} catch (IOException e) {
Log.e("a", "Error while calling web services " +e);
e.printStackTrace();
}
}
// return JSON Object
return jObj;
}
/* Call the web service and get JSON Object response */
public JSONObject getResponseAsJSON (String URL, ArrayList <NameValuePair> params)
{
return responseToJSON(getWebServiceResponse(URL,params));
}
}
这篇关于Android服务与REST风格的Web服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!