【问题标题】:Make asynchrone request发出异步请求
【发布时间】:2011-12-13 20:15:13
【问题描述】:

我正在使用此代码从 Restful Web 服务获取 json 字符串

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;
    }

我得到了我想要的,但我想知道,这个方法是同步的还是异步的?请求运行时应用程序将被阻止或在后台调用 Web 服务?

我在*中创建了这个方法,不需要的代码太多了;我不使用参数,有没有更简单的方法??

【问题讨论】:

    标签: java android json web-services


    【解决方案1】:

    好吧,如果你不使用参数,你可以将 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;
    }
    

    【讨论】: