我需要在android java中調用webservice,而另一個類調用它。最後,顯示UI中的ws響應。在Android中調用Async Restfull WebService
我已經完成了web服務。只有「異步」的那部分工作不正常。
這是我的web服務,接受三個字符串:
public class WebServiceRestFull extends AsyncTask<String, String, String>
{
protected ProgressDialog dialog;
public String wsURL;
public String wsFunction;
public String wsInput;
public int codeHTTP;
public String messageHTTP;
public String strResponse;
public WebServiceRestFull(Context act)
{
dialog = new ProgressDialog(act);
}
@Override
protected void onPreExecute() {
dialog.setMessage("Wait please...");
dialog.show();
}
@Override
protected void onPostExecute(String result)
{
if (dialog.isShowing())
{
dialog.dismiss();
}
}
@Override
protected String doInBackground(String... params)
{
String url = wsURL + wsFunction;
String inputCoded = EncodeString(wsInput);
HttpURLConnection request;
URL urlToRequest = new URL(url);
request = (HttpURLConnection) urlToRequest.openConnection();
request.setDoOutput(true);
request.setDoInput(true);
request.setRequestProperty("Content-Type", "application/json");
request.setRequestMethod("POST");
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(request.getOutputStream());
outputStreamWriter.write("\""+inputCoded+"\"");
outputStreamWriter.flush();
outputStreamWriter.close();
codeHTTP = request.getResponseCode();
messageHTTP = request.getResponseMessage();
InputStream is = request.getInputStream();
String resp = convertStreamToString(is);
strResponse = DecodeString(resp);
request.disconnect();
return strResponse;
}
catch (Exception ex)
{
ex.printStackTrace();
return "ERROR";
}
}
}
另一方面,在 「Android的活動」 我把這種異步類,如下所示:
WebServiceRestFull web = new WebServiceRestFull(this);
web.wsURL = "http://someurl.com/rest/etc";
web.wsFunction = "login";
web.wsInput = "mike";
web.execute();
Thread.sleep(1000);
問題是,這實際上不是一個異步調用,並且結果通常不會被web服務接收。
是否有任何簡單的方法來做到這一點,或者我做錯了一些方面的調用Web服務或自己的Web服務類?
對不起,我的英語。
謝謝!
爲什麼使用Thread.sleep(1000)?而是使用回調方法來獲得結果後的結果。 – Muthu