2011-03-10 60 views
0

在我的Java程序中,我想從使用Http基本驗證的服務器下載文件。我可以爲此使用java.net包的URL類嗎?如果不是,我應該使用哪個java類?涉及HTTP基本驗證的文件下載

請幫助 謝謝

回答

1

是,您可以:

 
final URL url = new URL(...); 
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 


if (username != null && username.trim().length() > 0 && password != null && password.trim().length() > 0) { 
    final String authString = username + ":" + password; 
    conn.setRequestProperty("Authorization", "Basic " + Base64.encodeBase64(authString.getBytes())); 
} 

conn.setRequestMethod("GET"); 
conn.setAllowUserInteraction(false); 
conn.setDoInput(false); 
conn.setDoOutput(true); 

final OutputStream outs = conn.getOutputStream(); 

... 

outs.close();