I want in download XML file for parsing?

2019-09-20 17:30发布

问题:

I am using using following code to download the file form receptive source

  private InputStream downloadUrl(String urlString) throws IOException {
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000 /* milliseconds */);
    conn.setConnectTimeout(15000 /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    // Starts the query  
    Log.v("Start Query", "Stream");
    conn.connect();
    Log.v("End Query", "Stream");
    InputStream stream = conn.getInputStream();    
    Log.v(stream.toString(), "Stream");
    return stream;
}

I got following erros in log

11-09 12:39:59.386: D/SntpClient(73): request time failed: java.net.SocketException: Address family not supported by protocol

回答1:

try the following:

      URL url = new URL(urlString);
      HttpURLConnection conn = (HttpURLConnection)url.openConnection();
      conn.setRequestMethod("GET");
      conn.setDoInput(true);
      conn.setReadTimeout(10000);
      conn.setConnectTimeout(15000);

      Log.v("Start Query", "Stream");          
      conn.connect();
      Log.v("End Query", "Stream");
      //read the result from the server
      BufferedReader rdr  = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      StringBuilder sbr = new StringBuilder();

      while ((line = rdr.readLine()) != null)
      {
          sbr.append(line + '\n');
      }

      Log.v(sbr.toString(), "Stream");