Java -HTTP URL连接下载文件为空

时间:2018-06-15 09:00:25

标签: java asp.net authorization httpurlconnection filestream

尝试使用java(HttpURLConnection类)从url下载文件(此服务在.net soap请求中开发)我正在使用空内容(即0kb)成功下载HttpURLConnection.HTTP_OK文件

代码:

        String userCredentials = "abc:cde";
        HttpURLConnection connection = (HttpURLConnection) url
                .openConnection();
        connection.setRequestProperty("Authorization","Basic "+ userCredentials);
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "Application/octet-stream");
        connection.setChunkedStreamingMode(4096);
        connection.setRequestProperty("SOAPAction", url.toString());

        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = connection.getInputStream();
            String saveFilePath = saveDir + File.separator + downloadFileName;
            System.out.println(saveFilePath);

            FileOutputStream outputStream = new FileOutputStream(saveFilePath);
            int bytesRead ;
            byte[] buffer = new byte[BUFFER_SIZE];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.close();
            inputStream.close();

输出:

HTTPResponse code : 200
File downloaded with empty 

注意:响应标题

{null=[HTTP/1.1 200 OK], Server=[Microsoft-IIS/8.5], Cache-Control=[private], X-AspNet-Version=[4.0.30319], Content-Length=[0], Date=[Fri, 15 Jun 2018 09:14:07 GMT], X-Powered-By=[ASP.NET]}

1 个答案:

答案 0 :(得分:-1)

您没有连接资源。 在connection.connect()句之前添加responseCode = httpurlconnection.http_ok