如何通过Java从URL下载和读取下载的文件

时间:2018-08-06 15:15:39

标签: java

我想通过Java在两个URL之间创建连接。我应该从一个URL中读取.docx文件中的信息,Java必须从URL中下载什么内容,然后再将这些信息发送到另一个URL中。我尝试通过以下方式阅读.docx:

import java.io.*;
import java.net.*;
import java.util.*;
import java.nio.*;

public class CheckList {

    public static void main(String[] args)throws Exception {
        String FILE = "https://exampleurl.com/download/2037";
        byte[] b = new byte[1];
        String username = "myusername";
        String password = "mypassword";
        Authenticator.setDefault(new MyAuthenticator(username, password));
        URL url = new URL(FILE);

        InputStream content = (InputStream) url.getContent();

        try{

       BufferedReader in = new BufferedReader(new InputStreamReader(content));
        String str;
         while ((str = in.readLine()) != null) {
          System.out.println(str);
         }
        }catch(IOException ex){ex.printStackTrace();}


    }

    static class MyAuthenticator extends Authenticator {
    private String login, password;

    public MyAuthenticator(String user, String pass) {
      login = user;
      password = pass;
    }

    protected PasswordAuthentication getPasswordAuthentication() {
      System.out.println("Requesting Host  : " + getRequestingHost());
      System.out.println("Requesting Port  : " + getRequestingPort());
      System.out.println("Requesting Prompt : " + getRequestingPrompt());
      System.out.println("Requesting Protocol: "
          + getRequestingProtocol());
      System.out.println("Requesting Scheme : " + getRequestingScheme());
      System.out.println("Requesting Site  : " + getRequestingSite());
      return new PasswordAuthentication(login, password.toCharArray());
    }
  }

}

但是不幸的是,它仅读取网站的JavaScript代码(用户必须登录的第一页)。有人可以建议我解决方案吗?

0 个答案:

没有答案