如何在asynctask中执行HTML get方法?

时间:2015-03-10 22:06:44

标签: android http android-asynctask get

我试图传递此方法来发出get请求并将数据作为String传递:

public String getdata(String url) throws ClientProtocolException,
        IOException {
    StringBuilder build = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    HttpResponse response = client.execute(httpGet);
    HttpEntity entity = response.getEntity();
    InputStream content = entity.getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            content));
    String con;
    while ((con = reader.readLine()) != null) {
        build.append(con);
    }
    return build.toString();
}

进入asynctask,因为我无法在主线程中运行它,我试图这样做但是#34; build"无法访问:

    public class getHTTPdata extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... url) {
        try {
            StringBuilder build = new StringBuilder();
            HttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    content));
            String con;
            while ((con = reader.readLine()) != null) {
                build.append(con);
            }
            return build.toString();

        } catch (IOException e) {
        }

        return build;
    }
}

我想将其视为:

getHTTPdata task = new getHTTPdata();
task.execute("myurl");

谢谢。

0 个答案:

没有答案