Java URL下载HTML内容而不是文件?

时间:2018-06-19 18:01:38

标签: java http url

我正在尝试使用Java URL类下载文件,但是它正在下载HTML内容。

{"username":"harry_potter"}

对于其他开放源URL,它可以正常工作,但只有在这种情况下(受密码保护),它才能下载HTML内容。

输出:

 class DownloadFileHttpCilent {

    public static void main(String[] args) throws Exception {

        try {
            CloseableHttpClient client = HttpClientBuilder.create().build();
            HttpGet request = new HttpGet(
                    "https://url");
            String encoding=Base64.getEncoder().encodeToString(("abcd:pwd").getBytes());
            request.setHeader("Authorization", "Basic " + encoding);

            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();

            int responseCode = response.getStatusLine().getStatusCode();

            System.out.println("Request Url: " + request.getURI());
            System.out.println("Response Code: " + responseCode);

            InputStream is = entity.getContent();

            String filePath = "c:\\file1.zip";
            FileOutputStream fos = new FileOutputStream(new File(filePath));

            int inByte;
            while ((inByte = is.read()) != -1) {
                fos.write(inByte);
            }

            is.close();
            fos.close();

            client.close();
            System.out.println("File Download Completed!!!");
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedOperationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }    
}

0 个答案:

没有答案