如何从android进行http调用

时间:2014-10-08 10:41:37

标签: java android

您好我想在线程中使用此代码,我该怎么做? 此代码用于在android中读取rss feed。

public String getXmlFromUrl(String url) {
    String xml = null;

    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);

    }
    catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    catch (ClientProtocolException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    // return XML
    return xml;
}

2 个答案:

答案 0 :(得分:0)

在网络操作上使用AsyncTask。这是一个例子:

private class YourTask extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... arg0) {

        String xml = null;

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);

        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        catch (ClientProtocolException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        // return XML
        return xml;
    }

    @Override
    protected void onPostExecute(String result) {
        // result is your xml. You can use it here.
    }

    @Override
    protected void onPreExecute() {}

    @Override
    protected void onCancelled() {}
}

您可以使用new YourTask().execute((Void)null);

调用此主题 祝你好运。

答案 1 :(得分:0)

在类字段中,定义一个处理程序,然后将代码放在下面的示例中;

Handler handler = new Handler();
... 

public void MyOnClick(View v){
    new Thread(new Runnable() {         
        @Override
        public void run() {
            handler.post(new Rubnable()){
                {your code}
            }
        }
    }).start();
}

最好的方法是使用AsyncTask ...