2011-12-13 5 views
-1

が、私はこのコードがasynchrone要求

WebService webService = new WebService("http://192.168.1.2:8080/data/resources/converter.user/"); 

Map<String, String> params = new HashMap<String, String>(); 
String response = webService.webGet("123333",params); 

//Use this method to do a HttpGet/WebGet on the web service 
    public String webGet(String methodName, Map<String, String> params) { 
     String getUrl = webServiceUrl + methodName; 

     int i = 0; 
     for (Map.Entry<String, String> param : params.entrySet()) 
     { 
      if(i == 0){ 
       getUrl += "?"; 
      } 
      else{ 
       getUrl += "&"; 
      } 

      try { 
       getUrl += param.getKey() + "=" + URLEncoder.encode(param.getValue(),"UTF-8"); 
      } catch (UnsupportedEncodingException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 


      i++; 
     } 

     httpGet = new HttpGet(getUrl); 
     Log.e("WebGetURL: ",getUrl); 

     try { 
      response = httpClient.execute(httpGet); 
     } catch (Exception e) { 
      Log.e("Groshie:", e.getMessage()); 
     } 

     // we assume that the response body contains the error message 
     try { 
      ret = EntityUtils.toString(response.getEntity()); 
     } catch (IOException e) { 
      Log.e("Groshie:", e.getMessage()); 
     } 

     return ret; 
    } 

とRESTfulなWebサービスからJSON文字列を取得していてください私は私が望む結果を得るが、私は、この方法はシンクロンかasynchronであれば、知りたいですか?要求が実行されているときにアプリケーションがブロックされるか、Webサービスがバックグラウンドで呼び出されますか?

私はこのメソッドをstackoverflowに作成しましたが、あまりにも多くの不要なコードがあります。私はparametresを使用しない、簡単な方法はありますか?

答えて

0

パラメータを使用しないと、コードブロックからforeachループを引き出すことができます。

(a)コードの同期性は、誰が呼び出しているかによって異なります。このクラスの独自のインスタンスをそれぞれ作成し、webGet()を呼び出す複数のスレッドを作成すると、非同期になります。あなたが何もせずにこれを呼び出して戻り値を返すmainメソッドを持っていれば、それは同期的で、ブロックされます。

可能なクリーンアップコード:

WebService webService = new WebService("http://192.168.1.2:8080/data/resources/converter.user/"); 

String response = webService.webGet("123333"); 

//Use this method to do a HttpGet/WebGet on the web service 
public String webGet(String methodName) { 
    String getUrl = webServiceUrl + methodName; 

    httpGet = new HttpGet(getUrl); 
    Log.e("WebGetURL: ",getUrl); 

    try { 
     response = httpClient.execute(httpGet); 
    } catch (Exception e) { 
     Log.e("Groshie:", e.getMessage()); 
    } 

    // we assume that the response body contains the error message 
    try { 
     ret = EntityUtils.toString(response.getEntity()); 
    } catch (IOException e) { 
     Log.e("Groshie:", e.getMessage()); 
    } 

    return ret; 
}