通过SSL使用HttpBuilder上传文件

时间:2014-01-23 05:24:01

标签: grails ssl groovy https httpbuilder

我正在尝试使用HttpBuilder将文件上传到通过SSL运行的Web服务。我是从Gradle构建文件中执行此操作但我不相信它真的很重要。 Web服务是Grails应用程序的一部分,但同样,不要认为这很重要。

当您告诉它通过https运行时,我的grails应用程序使用grails生成的证书在本地运行SSL。我在本地工作的代码如下:

def http = new groovyx.net.http.HTTPBuilder( 'https://localhost:8443/' )

//=== SSL UNSECURE CERTIFICATE ===
def sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, [ new X509TrustManager() {
  public X509Certificate[] getAcceptedIssuers() {null }
  public void checkClientTrusted(X509Certificate[] certs, String authType) { }
  public void checkServerTrusted(X509Certificate[] certs, String authType) { }
} ] as TrustManager[], new SecureRandom())
def sf = new SSLSocketFactory(sslContext)
def httpsScheme = new Scheme("https", sf, 8443)
http.client.connectionManager.schemeRegistry.register( httpsScheme )

http.request( groovyx.net.http.Method.POST, groovyx.net.http.ContentType.JSON ) { req ->
    uri.path = '/a/admin/runtime/upload'
    uri.query = [ username: "username", password: "password", version: version]
    requestContentType = 'multipart/form-data'
    org.apache.http.entity.mime.MultipartEntity entity = new org.apache.http.entity.mime.MultipartEntity()
    def file = new File("file.zip")
    entity.addPart("runtimeFile", new org.apache.http.entity.mime.content.ByteArrayBody(file.getBytes(), 'file.zip'))
    req.entity = entity
}

顶部的所有垃圾都是我发现的一些代码,它允许HttpBuilder使用自签名证书。这实际上是在本地工作。 HttpBuilder文档说,大多数时候,SSL应该“正常工作”。因此,我通过SSL购买认证的代码如下:

def http = new groovyx.net.http.HTTPBuilder( 'https://www.realserver.com/' )

http.request( groovyx.net.http.Method.POST, groovyx.net.http.ContentType.JSON ) { req ->
    uri.path = '/a/admin/runtime/upload'
    uri.query = [ username: "username", password: "password" ]
    requestContentType = 'multipart/form-data'
    org.apache.http.entity.mime.MultipartEntity entity = new org.apache.http.entity.mime.MultipartEntity()
    def file = new File("file.zip")
    entity.addPart("runtimeFile", new org.apache.http.entity.mime.content.ByteArrayBody(file.getBytes(), 'file.zip'))
    req.entity = entity
}

当我运行时,我收到以下错误:

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

非常感谢任何提示或建议。

1 个答案:

答案 0 :(得分:0)

这可能是因为该服务正在使用HTTPS的自签名证书。要正确地与其进行交互,您应该使用cacerts将其导入JRE的keytool文件。示例命令如下所示:

keytool -import -alias serviceCertificate -file ServiceSelfSignedCertificate.cer -keystore {path/to/jre/lib/security/cacerts}