Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I want to use this code in thread < How I can do this ??
Java
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;
    }
Posted

1 solution

Wrap it in an AsyncTask;

public class GetXmlTask extends AsyncTask<String, Void, String> {
     @Override
     protected String doInBackground(String...urls) {
         String url = urls[0]; // Might want to handle more here
         return getXmlFromUrl(url);
     }

     @Override
     protected void onPostExecute(String result) {
       // This runs on the ui thread when done, put your logic that works
       // on the result here
     }

     @Override
     protected void onPreExecute() {
     }

     @Override
     protected void onProgressUpdate(Void... values) {
     }

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


Then call that like new GetXmlTask().execute("http://google.com");.

You can get more details on AsyncTask[^].

Hope this helps,
Fredrik
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900