超时http请求? Android的

时间:2014-09-10 14:08:47

标签: java android xml http

我有以下代码,它转到一个url并从页面中提取xml;将其返回到调用页面;然后它被绑定到listView。

我遇到的问题是有时连接被拒绝,或连接需要一段时间才能建立。因此,应用程序有时不会将任何数据带回40秒以上,因为它正在等待成功连接。

我的问题是,如果给出以下代码,如果它尝试超过3秒钟,我将如何超时httpconnection?

这样,如果它无法成功连接,它将移动到下一个URl;而不是留在当前的一段时间。

任何建议都会有所帮助!

谢谢!

代码:

package com.example.directrssread;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.util.Log;

public class XMLParser {

    // constructor
    public XMLParser() {

    }

    /**
     * Getting XML from URL making HTTP request
     * @param url string
     * */
    public String getXmlFromUrl(String url) {
        String xml = null;

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


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

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

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

            DocumentBuilder db = dbf.newDocumentBuilder();
            dbf.setCoalescing(true);   
            if (db!=null)
            {
            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;
    }

    /** Getting node value
      * @param elem element
      */
    public final String getElementValue2( 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  ){  
                     if( child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE  ){       
                        return child.getNodeValue();  
                    }  
                }  
            }  
        }  
        return "";  
        //return elem.getTextContent();  
    } 

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


}

1 个答案:

答案 0 :(得分:0)

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

        try {
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 3000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

            //HttpPost httpPost = new HttpPost(url);
            HttpGet httpPost = new HttpGet(url);


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

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