gpt4 book ai didi

android - XML 解析器无连接错误

转载 作者:太空狗 更新时间:2023-10-29 14:27:14 24 4
gpt4 key购买 nike

我的 XML 解析器 在我有连接时工作得很好,如果它丢失我的 Activity 将崩溃我想要一个警告对话框弹出窗口说连接丢失而不是 Activity 崩溃但我这样做不知道该怎么做。

任何见解都会有所帮助

    public class XMLParser {

// constructor
public XMLParser() {

}

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


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

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

public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}

最佳答案

上述方法不一定总是有效。这个是万无一失的

private boolean isOnline() {
try {
myurl = new URL("http://m.google.com");
} catch (MalformedURLException e2) {
e2.printStackTrace();
}
try {
connection = myurl.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setConnectTimeout(3000);
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = -1;
try {
responseCode = httpConnection.getResponseCode();
} catch (Exception e1) {
e1.printStackTrace();
}
if (!(responseCode == HttpURLConnection.HTTP_OK))
{
return false;
}
return true;

关于android - XML 解析器无连接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11070312/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com