【发布时间】:2014-06-13 07:02:45
【问题描述】:
我是安卓新手。我需要从我的应用程序调用 RestFull 网络服务。 我可以从 android 服务调用 RestFull Web 服务吗?如果是,那么它是如何实现的?
【问题讨论】:
标签: android web-services webservice-client
我是安卓新手。我需要从我的应用程序调用 RestFull 网络服务。 我可以从 android 服务调用 RestFull Web 服务吗?如果是,那么它是如何实现的?
【问题讨论】:
标签: android web-services webservice-client
在 android 中直接通过 HTTP 方法使用 Webservices 会导致 ANR(Android 无响应)异常和 Network On Main Thread 异常。因此,您必须使用 ASYNCTASK 来调用 /consume web-services。
需要权限:
<uses-permission android:name="android.permission.INTERNET" />
代码 sn-p:
这是 android 客户端中的主要活动。从这里开始,Web 服务将在某个特定触发器上使用,例如用户单击一个按钮。 使用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 Consuming (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 应用程序是单线程应用程序,这意味着应用程序将在一个且唯一的线程上运行,如果您尝试从该线程调用 HTTP 操作,它将给您异常。要进行网络操作,例如调用 Restfull Web 服务或其他一些网络操作,您需要创建一个扩展 AsyncTask 的类。
这里是示例代码。
public class AsyncInvokeURLTask extends AsyncTask<Void, Void, String> {
private final String mNoteItWebUrl = "your-url.com";
private ArrayList<NameValuePair> mParams;
private OnPostExecuteListener mPostExecuteListener = null;
public static interface OnPostExecuteListener{
void onPostExecute(String result);
}
AsyncInvokeURLTask(
ArrayList<NameValuePair> nameValuePairs,
OnPostExecuteListener postExecuteListener) throws Exception {
mParams = nameValuePairs;
mPostExecuteListener = postExecuteListener;
if (mPostExecuteListener == null)
throw new Exception("Param cannot be null.");
}
@Override
protected String doInBackground(Void... params) {
String result = "";
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(mNoteItWebUrl);
try {
// Add parameters
httppost.setEntity(new UrlEncodedFormEntity(mParams));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null){
InputStream inStream = entity.getContent();
result = convertStreamToString(inStream);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String result) {
if (mPostExecuteListener != null){
try {
JSONObject json = new JSONObject(result);
mPostExecuteListener.onPostExecute(json);
} catch (JSONException e){
e.printStackTrace();
}
}
}
private static String convertStreamToString(InputStream is){
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
您可以在 Android 官方网站上阅读更多关于 AsyncTask here 的信息。
附:代码取自here。
【讨论】: