我已经编写了以下 java 代码来从使用 http 基本身份验证的服务器下载文件。但是我收到了 Http 401 错误。不过,我可以通过直接从浏览器中点击 url 来下载文件。
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)
不过,我可以通过点击 url http://username:password@somehost/protected-area/somefile.doc 下载文件。 ,直接从浏览器。
是什么导致了这个问题,有什么办法可以解决?
请帮忙 谢谢。
最佳答案
我正在使用 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);
等...
关于java - 从我的 java 代码使用基本 http 身份验证的服务器下载文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5258844/