将 XML 下载到字符串



我尝试使用以下代码下载XML:

 @Override
 protected String doInBackground(String... params) {
      try {    
           URL url = new URL("http://xx.xx.xx.xx/1.xml");
           URLConnection ucon = url.openConnection();
           ucon.setRequestProperty("Accept", "application/xml");
           InputStream is = ucon.getInputStream();
           BufferedInputStream bis = new BufferedInputStream(is);
           ByteArrayBuffer baf = new ByteArrayBuffer(50);
           int current = 0;
           while ((current = bis.read()) != -1) {
                baf.append((byte) current);
           }
           String str = new String(baf.toByteArray(), "UTF8");
           return str;
      } catch (MalformedURLException e) {
           Log.e(DEBUG_TAG, "6",e);
      } catch (IOException e) {
           Log.e(DEBUG_TAG, "7",e);
      }
      return "error";
 }

我收到错误:

12-12 08:12:15.434: 错误/myLogs(10977): java.io.FileNotFoundException: http://xx.xx.xx.xx/1.xml

如果我在浏览器中打开此网址,请参阅:

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Home>
<Child sex="male" age="5" name="Vasya"/>
<pets>
<Dog age="3" name="Druzshok"/>
</pets>
</Home>

我猜你的服务器拦截了一些请求.

例如:

选中标题中的 [用户代理]。

ucon.setRequestProperty("Accept", "application/xml");  remove the line..

您想知道为什么 java URL 对象抛出一个未找到的文件? 这意味着服务器以"404 未找到"响应您的请求,或者出于某种原因服务器没有给出响应。

所以你想知道为什么当你在浏览器中访问它时它工作正常,因为服务器对浏览器的处理方式与脚本不同。 首先尝试将用户代理设置为与您的浏览器相同。 如今,服务器越来越多地打击机器人,因为不礼貌的脚本作者敲打他们的网站。

源:java.io.FileNotFoundException for valid URL

may server filter ['User-Agent']。法典:

@Override
protected String doInBackground(String... params) {
    try {
        URL url = new URL("http://xx.xx.xx.xx/1.xml");
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setUseCaches(false);
        conn.setReadTimeout(60 * 1000);
        conn.setConnectTimeout(30*1000);
        conn.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:39.0) Gecko/20100101 Firefox/39.0");
        BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream(),"UTF-8"));
        StringBuilder buf = new StringBuilder(512);
        String line = null;
        while((line=reader.readLine())!=null){
            buf.append(line).append("n");
        }
        conn.disconnect();
        return buf.toString();
    }  catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}