发出异步请求

时间:2011-12-13 20:15:13

标签: java android json web-services

我使用此代码从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服务?

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

1 个答案:

答案 0 :(得分: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;
}