使用Post请求在HTTP客户端中启用TLS

时间:2016-06-29 11:39:15

标签: java sockets ssl tls1.2

我想将TLS 1.2添加到下面的代码中,尝试创建套接字但没有运气。有人可以帮忙吗?我们可以在创建客户端后添加它吗?

  private static int executeSOAPRequest(String req, String targetURL)
        throws Exception {
    PostMethod post = new PostMethod(targetURL);
    post.setRequestBody(req);
    post.setRequestHeader("Content-type",
            "text/xml; characterset=ISO-8859-1");
    post.setRequestHeader("SOAPAction", "\"\"");

    // prepare HTTP Client
    HttpClient client = new HttpClient();
    client.getParams().setParameter("SOAPAction", "\"\"");

    // Post the request
    int respCode = client.executeMethod(post);
    System.out.println(post.getResponseBodyAsString());
    // If response is not success
    if (respCode != 200)
        throw new Exception("Executing SOAP request has failed.");
    // Convert the response into NOM XML
    int resp = 0;
    Document doc = nomDocPool.lendDocument();
    try {
        resp = doc.parseString(post.getResponseBodyAsString());
        nomDocPool.returnDocument(doc);
    } catch (XMLException e) {
        nomDocPool.returnDocument(doc);
        //logger.error("Exception while generating SAML : "
                //+ e);
        throw e;
    }
System.out.println("resp: "+resp);
    return resp;
}

1 个答案:

答案 0 :(得分:0)

HttpClient已经为您处理了TLS。记录在案:

http://hc.apache.org/httpclient-3.x/sslguide.html

  

HttpClient通过利用Java安全套接字扩展(JSSE)为安全套接字层(SSL)或IETF传输层安全性(TLS)协议提供HTTP的完全支持。从版本1.4开始,JSSE已经集成到Java 2平台中,并且可以与HttpClient一起使用。

您所要做的就是确保targetURL使用https://代替http://,然后HttpClient为您处理其余部分。