无法使用spring下载文件,没有错误,但代码不工作



我正试图通过身份验证从服务器下载文件,下面是我的Java代码,但我无法下载文件,但代码运行没有错误首先使用trustSelfSignedSSL();我将禁用ssl握手和使用http实体头后,我发送凭据

问题可能只在主方法

public class AppTest
{
    public static void main(String arg[]) throws IOException
    {
        ArrayList<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
        messageConverters.add(new ByteArrayHttpMessageConverter());
        AppTest.trustSelfSignedSSL();
         RestTemplate restTemplate = new RestTemplate(messageConverters);

           System.out.println("ok");

            ResponseEntity<byte[]> response = restTemplate.exchange(
                    "https://jira.example.com/rest/api/2/issue/id",
                    HttpMethod.GET, new HttpEntity<String>(createHeaders()), byte[].class, "1");
            System.out.println(response.getBody());
            if (response.getStatusCode() == HttpStatus.OK) {
                System.out.println("inside");
                Files.write(Paths.get("file.html"), response.getBody());
            }

    }
    static HttpHeaders createHeaders(){
        String plainCreds = "user:pass";
        byte[] plainCredsBytes = plainCreds.getBytes();
        byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
        String base64Creds = new String(base64CredsBytes);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic " + base64Creds);
        return headers;
    }
    public static void trustSelfSignedSSL() {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
                }
                public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
                }
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLContext.setDefault(ctx);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

}
}

我验证了您的SSL绕过和基本身份验证,它们看起来不错。我以前成功地使用过这个技巧。

我怀疑的是RestTemplate调用。

ResponseEntity<byte[]> response = restTemplate.exchange(              
    "https://jira.example.com/rest/api/2/issue/id",                      
    HttpMethod.GET, new HttpEntity<String>(createHeaders()), byte[].class, "1");

"1"参数在最后假设是uriVariable,但你的URL没有任何占位符(例如https://jira.example.com/rest/api/2/issue/{id})。尝试删除最后一个参数

最新更新