2016-07-05 61 views
0

我需要在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服務類?

對不起,我的英語。

謝謝!

+0

爲什麼使用Thread.sleep(1000)?而是使用回調方法來獲得結果後的結果。 – Muthu

回答

0

沒有什麼是錯的方式創建和excecuted此的AsyncTask

只是請不要使用Thread.sleep()方法;

而問題顯然是在doInBackground()方法的代碼,我們沒有在這裏

+0

我使用該代碼編輯了我的問題。 – user3178284

+0

嘗試觀看日誌,如果在請求期間有問題,應該有一些警告 –

0

是您的代碼完成?在你的課堂上沒有任何東西可以提出http請求,其餘的似乎沒有問題。 嘗試使用Okhttp它非常簡單。檢查它here

該線程睡眠將在主線程運行,這不是很好的主意。使用後執行來運行你回調和發佈任何結果。

相關問題