【发布时间】:2016-01-07 16:47:52
【问题描述】:
我有以下代码使用 httpclient 从 URL 下载文件。尽管该程序可以运行,但每次我运行它时它只下载 3k。 我已经设置了一些代理来克服公司网络,并正在尝试使用下面的代码来自动从外部网站下载。
该网站还有一些其他文件(如视频、音频)。即使我尝试使用它们,大小也是 3k。我正在使用他们的 REST 接口来获取文件。我需要在我的代码中进行一些更改以使其仍能正常工作吗?
url = "https://samforloogin.com/video.zip";
URI uri = URI.create(url);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
CloseableHttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.build();
HttpGet httpGet = new HttpGet(uri);
httpGet.setHeader("Authorization", "Basic " + encoding);
CloseableHttpResponse response = httpclient.execute(httpGet);
java.io.InputStream is = response.getEntity().getContent();
String filePath = "C:\\Users\\smandodd\\AppData\\Local\\Temp\\8ee47df6c5a44c9d9c8ff3326d932819\\screenshots.flv";
FileOutputStream fos = new FileOutputStream(new File(filePath ));
int inByte;
while((inByte = is.read()) != -1) {
System.out.println("The number of bytes read are" + inByte);
fos.write(inByte);
}
is.close();
fos.close();
【问题讨论】:
-
您在
screenshots.flv中看到了什么文字?它可能是一些指示 HTTP 错误的文本。 -
当你在调试器中运行时你看到了什么?您已经在调试器中运行它,不是吗?
-
@MartinKonecny 谢谢你的文件确实有错误信息...
-
现在可以正常使用下面的更新
CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope("proxy-aep.com", 8080), new UsernamePasswordCredentials("myself", "mypassword")); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); CloseableHttpClient httpclient = HttpClients.custom() .setRoutePlanner(routePlanner) .setDefaultCredentialsProvider(credsProvider) .build();
标签: java rest httpclient