使用Java HttpsURLConnection进行授权下载的问题

时间:2018-01-31 20:36:44

标签: java

我正在尝试使用带有Authorization标头的java HttpsURLConnection从https网站下载文件。我一直收到401响应代码,但是,使用凭据通过Web浏览器下载它我没有问题。请帮忙看看我的代码可能有什么问题:

File file = new File("c:/filename"); 
String src = "https://www.example.com/filename";
try {
    file.createNewFile();       
    URL url = new URL(src);
    HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection();


    String userCredentials = "username:password";
    String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
    urlConnection.addRequestProperty ("Authorization", basicAuth);
    urlConnection.connect();

    System.out.println("code" + urlConnection.getResponseCode());

    InputStream in = urlConnection.getInputStream();
    OutputStream out = new FileOutputStream(file);
    int d;
    while ((d = in.read()) != -1) {
        out.write(d);
    }
    in.close();
    out.close();
} catch (Exception e) {
    System.err.println("Failed to get the file from source. " + e);
    if (file.exists()) {
        file.delete();
    }
} 

0 个答案:

没有答案