使用 HttpURL 从网址下载文件 |HTTP 400(如果文件名包含空格)



我正在尝试使用 http 连接从 url(soap 请求(下载文件,下面是我的代码,在执行时我得到 http = 400,因为文件名包含空格(ac abc.pdf)

String downloadFileName = "ac abc.pdf";
String saveDir = "D:/download";
String baseUrl = "abc.com/AttachmentDownload?Filename=";
URL url = new URL(baseUrl + downloadFileName);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setReadTimeout(60 * 1000);
connection.setConnectTimeout(60 * 1000);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/octet-stream");
connection.setRequestProperty("SOAPAction", url.toString());
String userCredentials = "user:pass";
connection.setRequestProperty("Authorization", userCredentials);
connection.setDoInput(true);
connection.setDoOutput(true);
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
try (InputStream inputStream = connection.getInputStream()) {
String saveFilePath = saveDir + downloadFileName;
try (FileOutputStream outputStream = new FileOutputStream(saveFilePath)) {
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
}

在执行上述代码时获取以下输出

responsecode400
response messageBad Request
No file to download. Server replied HTTP code: 400

让我知道我们如何在上述情况下格式化 URL

空格和其他一些符号在 URL 中没有很好地引用。您需要转义或编码它们更改代码

URL url = new URL(baseUrl + downloadFileName);

自:

URL url = new URL(baseUrl + URLEncoder.encode(downloadFileName, StandardCharsets.UTF_8.name());

这应该可以解决您的问题。此外,还有开源库可以为您解决问题。参见Apache commons,这是一个流行的解决方案。另一种解决方案是MgntUtils库(版本1.5.0.2(。它包含类HttpClient,允许您做非常简单的事情:

httpClient.sendHttpRequestForBinaryResponse(baseUrl + URLEncoder.encode(downloadFileName, StandardCharsets.UTF_8.name()", HttpClient.HttpMethod.POST);

这将返回包含原始字节响应的字节缓冲区。同一类具有获取文本响应的方法sendHttpRequest。这两种方法都会在失败时抛出IOException。这是一篇文章的链接,该文章解释了从哪里获得MgntUtils库以及它具有哪些实用程序。在文章中没有提到HttpClient类(这是一个新功能(,但库附带了编写良好的javadoc。因此,请在该库中查找 HttpClient 类的 javadoc。

最新更新