我编写了以下java代码,用于从使用http基本身份验证的服务器下载文件。但是我得到了Http 401错误。我可以通过直接从浏览器点击网址来下载文件。
OutputStream out = null;
InputStream in = null;
URLConnection conn = null;
try {
// Get the URL
URL url = new URL("http://username:password@somehost/protected-area/somefile.doc");
// Open an output stream for the destination file locally
out = new BufferedOutputStream(new FileOutputStream("file.doc"));
conn = url.openConnection();
in = conn.getInputStream();
// Get the data
byte[] buffer = new byte[1024];
int numRead;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
}
} catch (Exception exception) {
exception.printStackTrace();
}
但是,当我运行程序时,我得到以下异常:
java.io.IOException: Server returned HTTP response code: 401 for URL: http://username:password@somehost/protected-area/somefile.doc
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1436)
at TestDownload.main(TestDownload.java:17)
然而,我可以通过直接从浏览器点击网址http://username:password@somehost/protected-area/somefile.doc来下载文件。
可能导致此问题的原因,以及解决问题的方法是什么?
请帮助 谢谢。
答案 0 :(得分:2)
我正在使用org.apache.http:
private StringBuffer readFromServer(String url) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
if (authState.getAuthScheme() == null) {
Credentials credentials = new UsernamePasswordCredentials(
Constants.SERVER_USERNAME,
Constants.SERVER_PASSWORD);
authState.setAuthScheme(new BasicScheme());
authState.setAuthScope(AuthScope.ANY);
authState.setCredentials(credentials);
}
}
};
httpclient.addRequestInterceptor(preemptiveAuth, 0);
HttpGet httpget = new HttpGet(url);
HttpResponse response;
InputStream instream = null;
StringBuffer result = new StringBuffer();
try {
response = httpclient.execute(httpget);
等...