简体   繁体   中英

Timeout http request? Android

I have the below code, which goes to a url and pulls the xml from the page; returning it to the calling page; where it is then bound to a listView.

The problem I have is that sometimes the connection is refused, or the connection takes a while to establish. So the app isn't bringing back any data for 40+ seconds sometimes, as it is waiting for a successful connection to be made.

My question is, is that given the below code, how would I time out the httpconnection if it has been trying for more than say 3 seconds?

This way, if it cannot make a successful connection, it will move onto the next URl; as opposed to staying on the current one for some time.

Any advice will be helpful!

Thanks!

Code:

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


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM