我是安卓新手。我需要从我的应用程序调用 RestFul Web 服务。 我可以从 android 服务调用 RestFul Web 服务吗?如果是,那么它是如何实现的?
最佳答案
在 Android 中直接通过 HTTP 方法使用 Web 服务会导致 ANR(Android 无响应)异常和 Network On Main Thread 异常。因此,您必须使用 ASYNCTASK 来调用/使用 Web 服务。
所需权限:
<uses-permission android:name="android.permission.INTERNET" />
代码 fragment :
这是 Android 客户端中的主要 Activity 。从这里开始,网络服务将在某些特定的触发器上使用,比如用户单击按钮。 使用AsyncTask用于在后台调用网络服务
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.
这是 WebServices 消费(POST REQUEST)的 HTTPClient 代码
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 服务与 RestFul Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24199494/