无法使用spring下载文件没有错误但代码无效

时间:2015-08-24 11:02:46

标签: java spring http resttemplate

我试图通过身份验证从服务器下载文件下面是我的java代码,但我无法下载文件,但代码运行没有错误 首先使用trustSelfSignedSSL();我将禁用ssl Handshake并在使用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();
        }



}
}

1 个答案:

答案 0 :(得分:1)

我验证了您的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,但您的网址没有任何占位符(例如https://jira.example.com/rest/api/2/issue/ {id})。尝试删除最后一个参数。