一个AsyncTask的内部HTTP请求 [英] HTTP Request inside an AsyncTask

查看:152
本文介绍了一个AsyncTask的内部HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个解析XML文件的HTTP请求。
我试图从asyntask连接到互联网,但我一直没能

我做到这一点,作品把code线程里面,但不是一个AsycTask内
我的问题是,HTTP请求与该行code的字符串中调用:

 字符串XML = parser.getXmlFromUrl(URL);

运行此

 公共字符串getXmlFromUrl(字符串URL){
            线程t =新的Thread(){
                公共无效的run(){
                    XML = NULL;
                    尝试{
                        Log.i(LOG1,解析);
                        // defaultHttpClient
                        DefaultHttpClient的HttpClient =新DefaultHttpClient();
                        HttpPost httpPost =新HttpPost(http://api.androidhive.info/music/music.xml);                        HTT presponse HTT presponse = httpClient.execute(httpPost);
                        HttpEntity httpEntity = HTT presponse.getEntity();
                        XML = EntityUtils.toString(httpEntity);                    }赶上(UnsupportedEncodingException五){
                        e.printStackTrace();
                    }赶上(ClientProtocolException E){
                        e.printStackTrace();
                    }赶上(IOException异常五){
                        e.printStackTrace();
                    }
                    mHandler.post(mUpdateResults);
                }
            };
            t.start();
            返回XML;
        }        最终的Runnable mUpdateResults =新的Runnable(){
            公共无效的run(){// 2            }
        };

正如我提到的那样,HTTP请求是在一个线程中,但我总能找到错误,当我试图把它里面AsycTask ......我不知道该怎么做。

我已经提到AsycTask的资料,看了很多次,我已搜查教程,但我不能正确地建立它。

两天后,我开始有点绝望

我把完整的code对我的工作,如果有人能告诉我如何更换AsyncTask的线索,我会很感激。

非常感谢你和问候

充分的活动:

 公共类PruebasActivity延伸活动{
    静态最终字符串URL =htt​​p://api.androidhive.info/music/music.xml;
    // XML节点键
        静态最后弦乐KEY_SONG =歌; //父节点
        静态最后弦乐KEY_ID =ID;
        静态最后弦乐KEY_TITLE =称号;
        静态最后弦乐KEY_ARTIST =艺术家;
        静态最后弦乐KEY_DURATION =时间;
        静态最后弦乐KEY_THUMB_URL =thumb_url;        私人的ArrayList<&HashMap的LT;字符串,字符串>>数据;
        ArrayList的<&HashMap的LT;字符串,字符串>> songsList;        ListView控件列表;
        LazyAdapter适配器;
        XML字符串;        最后的处理程序mHandler =新的处理程序();
        //构造
        公共无效XMLParser的(){        }        / **
         * Cogiendo埃尔XML德拉URL mediante HTTP请求
         * @参数的URL字符串
         * * /
        公共字符串getXmlFromUrl(字符串URL){
            线程t =新的Thread(){
                公共无效的run(){
                    XML = NULL;
                    尝试{
                        Log.i(LOG1,解析);
                        // defaultHttpClient
                        DefaultHttpClient的HttpClient =新DefaultHttpClient();
                        HttpPost httpPost =新HttpPost(http://api.androidhive.info/music/music.xml);                        HTT presponse HTT presponse = httpClient.execute(httpPost);
                        HttpEntity httpEntity = HTT presponse.getEntity();
                        XML = EntityUtils.toString(httpEntity);                    }赶上(UnsupportedEncodingException五){
                        e.printStackTrace();
                    }赶上(ClientProtocolException E){
                        e.printStackTrace();
                    }赶上(IOException异常五){
                        e.printStackTrace();
                    }
                    mHandler.post(mUpdateResults);
                }
            };
            t.start();
            返回XML;
        }        最终的Runnable mUpdateResults =新的Runnable(){
            公共无效的run(){// 2            }
        };        / *
         * @参数XML字符串
         * * /
        公开文件getDomElement(字符串XML){
            文档DOC = NULL;
            DBF的DocumentBuilderFactory = DocumentBuilderFactory.newInstance();
            尝试{                的DocumentBuilder分贝= dbf.newDocumentBuilder();                InputSource的是=新的InputSource();
                is.setCharacterStream(新StringReader(XML));
                DOC = db.parse(是);            }赶上(的ParserConfigurationException E){
                Log.e(错误,e.getMessage());
                返回null;
            }赶上(SAXException的E){
                Log.e(错误,e.getMessage());
                返回null;
            }赶上(IOException异常五){
                Log.e(错误,e.getMessage());
                返回null;
            }            返回文档;
        }        / *
         * @参数ELEM元素
         * /
        公共最后弦乐getElementValue(节点ELEM){
            子节点;
            如果(ELEM!= NULL){
                如果(elem.hasChildNodes()){
                    对于(孩子= elem.getFirstChild(!);孩子= NULL;孩子= child.getNextSibling()){
                        如果(child.getNodeType()== Node.TEXT_NODE){
                            返回child.getNodeValue();
                        }
                    }
                }
            }
            返回;
        }        / *
         * @参数Element节点
         * @参数密钥字符串
         * * /
        公共字符串的getValue(元素项,字符串str){
            节点列表N = item.getElementsByTagName(STR);
            返回this.getElementValue(n.item(0));
        }    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);        名单=(ListView控件)findViewById(R.id.list);        songsList =新的ArrayList<&HashMap的LT;字符串,字符串>>();        XMLParser的解析器=新XMLParser的();
        字符串XML = parser.getXmlFromUrl(URL); // Cogiendo XML德拉网址
        文档的文档= parser.getDomElement(XML); // Cogiendo DOM德洛斯elementos        节点列表NL = doc.getElementsByTagName(KEY_SONG);
        //遍历所有歌曲节点&LT循环;宋>
        的for(int i = 0; I< nl.getLength();我++){
            //创建新的HashMap
            HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();
            元素e =(元)nl.item(I)
            //将每个子节点的HashMap键=>值
            map.put(KEY_ID,parser.getValue(即KEY_ID));
            map.put(KEY_TITLE,parser.getValue(即KEY_TITLE));
            map.put(KEY_ARTIST,parser.getValue(即KEY_ARTIST));
            map.put(KEY_DURATION,parser.getValue(即KEY_DURATION));
            map.put(KEY_THUMB_URL,parser.getValue(即KEY_THUMB_URL));            //添加HashList到ArrayList的
            songsList.add(地图);
        }        // Pasando DATOS parseados德尔adaptador人的ArrayList
        适配器=新MinAdapter(这一点,songsList);
        list.setAdapter(适配器);
    }
}


解决方案

HTTP请求可以的AsyncTask的doInBackground函数运行,您可运行是onPostExecute功能。
结果是这样的:

 公共类XmlTask​​扩展的AsyncTask<弦乐,太虚,字符串> {    公共字符串doInBackground(字符串的URL ...){
        字符串URL =网址[0];        //此处将您getXmlFromUrl内容        返回XML;
    }    公共无效onPostExecute(字符串XML){
        //你的XML解析staement这里
    }
}

在此code,螺纹和可运行的都是不必要的。

而在你活动只需轻按:

 新XmlTask​​()执行(HTTP:// yourURL的);

I have an HTTP Request that parses an XML file. I'm trying to connect to internet from an asyntask but I have not been able

I do this and works by putting the code inside a thread, but not inside an AsycTask The problem I have is that the HTTP Request is called within a String with this line of code:

String xml = parser.getXmlFromUrl(URL);

Running this

public String getXmlFromUrl(String url) {
            Thread t= new Thread(){
                public void run() {
                    xml = null;              
                    try {
                        Log.i("Log1","Parse");
                        // defaultHttpClient
                        DefaultHttpClient httpClient = new DefaultHttpClient();
                        HttpPost httpPost = new HttpPost("http://api.androidhive.info/music/music.xml");

                        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();
                    }
                    mHandler.post(mUpdateResults);
                }
            };
            t.start();
            return xml;
        }

        final Runnable mUpdateResults =new Runnable (){
            public void run(){//2

            }
        };

As I mentioned, the HTTP Request is within a thread, but I always find errors when I try to put it inside a AsycTask ... I do not know how do it.

I have been referred to the documentation of AsycTask and have read many times, I have searched tutorials, but I could not build it correctly.

After two days, i begin to be a little desperate

I put the complete code for my work, if anyone can tell me how to replace a AsyncTask thread, I'll be very grateful.

Thank you very much and regards

full activity:

public class PruebasActivity extends Activity {


    static final String URL = "http://api.androidhive.info/music/music.xml";
    // XML node keys
        static final String KEY_SONG = "song"; // parent node
        static final String KEY_ID = "id";
        static final String KEY_TITLE = "title";
        static final String KEY_ARTIST = "artist";
        static final String KEY_DURATION = "duration";
        static final String KEY_THUMB_URL = "thumb_url";

        private ArrayList<HashMap<String, String>> data;
        ArrayList<HashMap<String, String>> songsList;

        ListView list;
        LazyAdapter adapter;
        String xml;

        final Handler mHandler=new Handler();


        // constructor
        public void XMLParser() {

        }

        /**
         * Cogiendo el XML de la URL mediante HTTP request
         * @param url string
         * */
        public String getXmlFromUrl(String url) {
            Thread t= new Thread(){
                public void run() {
                    xml = null;              
                    try {
                        Log.i("Log1","Parse");
                        // defaultHttpClient
                        DefaultHttpClient httpClient = new DefaultHttpClient();
                        HttpPost httpPost = new HttpPost("http://api.androidhive.info/music/music.xml");

                        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();
                    }
                    mHandler.post(mUpdateResults);
                }
            };
            t.start();
            return xml;
        }

        final Runnable mUpdateResults =new Runnable (){
            public void run(){//2

            }
        };

        /*
         * @param XML string
         * */
        public Document getDomElement(String xml){
            Document doc = null;
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            try {

                DocumentBuilder db = dbf.newDocumentBuilder();

                InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc = db.parse(is); 

            } catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (SAXException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (IOException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }

            return doc;
        }

        /*
         * @param elem element
         */
        public final String getElementValue( Node elem ) {
            Node child;
            if( elem != null){
                if (elem.hasChildNodes()){
                    for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                        if( child.getNodeType() == Node.TEXT_NODE  ){
                            return child.getNodeValue();
                        }
                    }
                }
            }
            return "";
        }

        /*
         * @param Element node
         * @param key string
         * */
        public String getValue(Element item, String str) {      
            NodeList n = item.getElementsByTagName(str);        
            return this.getElementValue(n.item(0));
        }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        list=(ListView)findViewById(R.id.list);

        songsList = new ArrayList<HashMap<String, String>>();

        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL); // Cogiendo XML de la URL
        Document doc = parser.getDomElement(xml); // Cogiendo DOM de los elementos

        NodeList nl = doc.getElementsByTagName(KEY_SONG);
        // looping through all song nodes <song>
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
            map.put(KEY_ID, parser.getValue(e, KEY_ID));
            map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
            map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
            map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
            map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));          

            // adding HashList to ArrayList
            songsList.add(map);
        }

        // Pasando datos parseados del adaptador al arrayList
        adapter=new MinAdapter(this, songsList);        
        list.setAdapter(adapter);   
    }
}

解决方案

The HTTP request can be run in the doInBackground function of Asynctask and your runnable is the onPostExecute function. The result is this :

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

    public String doInBackground(String... urls){
        String url = urls[0];

        // Place your getXmlFromUrl content here

        return xml;
    }

    public void onPostExecute(String xml){
        // Your XML parsing staement here
    }
}

In this code, Thread and runnable are unnecessary.

And in your activity just tap:

new XmlTask().execute("http://yoururl");

这篇关于一个AsyncTask的内部HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆