从未返回的有效URL读取XML。标题格式问题?

时间:2014-06-20 20:19:54

标签: java url file-io http-headers

我正在尝试使用以下代码从有效网址中读取。我可以将url复制并粘贴到我的浏览器中,它可以正常工作(显示xml),但是当我尝试以编程方式访问它时,它什么都不返回(没有数据也没有错误)。我已经尝试通过这篇文章设置用户代理:Can't read in HTML content from valid URL但它没有解决我的问题。如果重要,我正在尝试进行一次Eve API调用。我认为问题是我没有正确格式化我的标题,并且Eve网站拒绝查询。我可以使用PHP访问数据,但最近我不得不更改语言。

    public static void readFileToXML(String urlString,String fName)
{
    try{
    java.net.URL url = new java.net.URL(urlString);
    System.out.println(url);
    URLConnection cnx = url.openConnection();
    cnx.setAllowUserInteraction(false);         
    cnx.setDoOutput(true);
    cnx.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/531.0 (KHTML, like Gecko) Chrome/3.0.183.1 Safari/531.0");
    System.out.println(cnx.getContentLengthLong());// a change suggested in the comments. returns -1
    InputStream is = cnx.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    File file=new File("C:\\Users\\xxx\\Desktop\\"+fName);
    BufferedWriter bw = new BufferedWriter(new FileWriter(file,false));
    String inputLine;
    while ((inputLine = br.readLine()) != null) {
        bw.write(inputLine);
        System.out.println(inputLine);
    }
    System.out.println("Finished read");
    bw.close();
    br.close();
    }
    catch(Exception e)
    {
        System.out.println("Exception: "+e.getMessage());
    }
}

0 个答案:

没有答案