当我的 api 级别设置为 8 时,一切正常。但是当我尝试将 minSdkVersion 设置为 11 时,我获取 xml 的 http 请求不起作用。我在 if 上得到了一个异常(exception)。 这是代码:
URL url;
String ciao="";
try {
url = new URL("myurl");
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(in);
DOMSource domSource = new DOMSource(dom);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
ciao=writer.toString();
}
}
catch(Exception e)
{
}
return ciao;
最佳答案
原因是,从 API 11 开始,您必须在后台线程上进行所有网络访问。否则,您将收到 NetworkOnMainThreadException
。这是为了防止 UI 在访问网络时无响应。
参见 here了解更多信息
关于android - 当我更改我的 api 级别时,我的 http 请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24136427/