I would like to configure a proxy server to my Jersey client.
I don't want to configure the proxy to the whole application (using JVM arguments such as http.proxyHost), and Id'e rather not use Apache client.
I read here that there is an option to do it by providing HttpUrlConnection
via HttpUrlConnectionFactory, but I couldn't find any code example.
Does anyone know how can I do it?
Thanks!
With the help of Luca, I got it done:
Implement HttpURLConnectionFactory, and override the method getHttpURLConnection, my implementation is (thanks to Luca):
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 3128));
return new HttpURLConnection(url, proxy);
Before instantiating the Jersey Client, create a new URLConnectionClientHandler, and provide your HttpURLConnectionFactory in its constructor. Then create a new Client, and provide your ClientHandler in the Client constructor. My code:
URLConnectionClientHandler urlConnectionClientHandler = new URLConnectionClientHandler(new MyHttpURLConnectionFactory());
_client = new Client(urlConnectionClientHandler);
Hope that's help.
First of all I created this class
import com.sun.jersey.client.urlconnection.HttpURLConnectionFactory;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
/**
*
* #author Aimable
*/
public class ConnectionFactory implements HttpURLConnectionFactory {
Proxy proxy;
String proxyHost;
Integer proxyPort;
SSLContext sslContext;
public ConnectionFactory() {
}
public ConnectionFactory(String proxyHost, Integer proxyPort) {
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
}
private void initializeProxy() {
proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
}
#Override
public HttpURLConnection getHttpURLConnection(URL url) throws IOException {
initializeProxy();
HttpURLConnection con = (HttpURLConnection) url.openConnection(proxy);
if (con instanceof HttpsURLConnection) {
System.out.println("The valus is....");
HttpsURLConnection httpsCon = (HttpsURLConnection) url.openConnection(proxy);
httpsCon.setHostnameVerifier(getHostnameVerifier());
httpsCon.setSSLSocketFactory(getSslContext().getSocketFactory());
return httpsCon;
} else {
return con;
}
}
public SSLContext getSslContext() {
try {
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{new SecureTrustManager()}, new SecureRandom());
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
} catch (KeyManagementException ex) {
Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
}
return sslContext;
}
private HostnameVerifier getHostnameVerifier() {
return new HostnameVerifier() {
#Override
public boolean verify(String hostname,
javax.net.ssl.SSLSession sslSession) {
return true;
}
};
}
}
then I also create another class called SecureTrustManager
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
/**
*
* #author Aimable
*/
public class SecureTrustManager implements X509TrustManager {
#Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
}
#Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
}
#Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public boolean isClientTrusted(X509Certificate[] arg0) {
return true;
}
public boolean isServerTrusted(X509Certificate[] arg0) {
return true;
}
}
then after creation this class i'm calling the client like this
URLConnectionClientHandler cc = new URLConnectionClientHandler(new ConnectionFactory(webProxy.getWebserviceProxyHost(), webProxy.getWebserviceProxyPort()));
client = new Client(cc);
client.setConnectTimeout(2000000);
replace webProxy.getWeserviceHost by your proxyHost and webProxy.getWebserviceProxyPort() by the proxy port.
This worked for me and it should work also for you. Note that i'm using Jersey 1.8 but it should also work for Jersey 2
Try
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
conn = new URL(url).openConnection(proxy);
Related
We were using socket.io server v2.3.0 without SSL. The js frontend client and the spring boot client were sending and receiving messages using that socket.io server.
Now, we are using SSL. The js frontend is working properly but the spring boot client does not emit any messages to the socket.io server. Here is my source code for emitting messages to the socket.io server. It was working without ssl. I changed the URL and set HTTPS for that.
IO.Options options = new IO.Options();
options.transports = new String[]{"websocket"};
options.reconnectionAttempts = 2;
options.reconnectionDelay = 1000;
options.timeout = 500;
final Socket socket = IO.socket(socketServerURL, options);
socket.on(Socket.EVENT_CONNECT, args1 -> socket.send("hello..."));
socket.on("connected", objects -> System.out.println("Server connected: " + objects[0].toString()));
socket.on("push_data_event", objects -> System.out.println("Server:" + objects[0].toString()));
socket.on("myBroadcast", objects -> System.out.println("Server:" + objects[0].toString()));
socket.connect();
socket.emit("chanel_name", message);
What is the problem? the versions are like the following:
Socket server:2.3.0
Socket js client: 2.3.0
Socket io-client: 1.0.0
The problem is solved by adding a static class and pass the options of the socket to this function. It adds some parameters to the option and solves the problem.
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import io.socket.client.IO;
import okhttp3.OkHttpClient;
public class SocketSSL {
public static OkHttpClient getOkHttpClient() {
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[]{new X509TrustManager() {
#Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
#Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
#Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}}, new java.security.SecureRandom());
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.hostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
builder.sslSocketFactory(sc.getSocketFactory(), new X509TrustManager() {
#Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
#Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
#Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
});
return builder.build();
} catch (NoSuchAlgorithmException | KeyManagementException ex) {
ex.printStackTrace();
}
return null;
}
public static void set(IO.Options options) {
OkHttpClient okHttpClient = getOkHttpClient();
IO.setDefaultOkHttpWebSocketFactory(okHttpClient);
IO.setDefaultOkHttpCallFactory(okHttpClient);
options.callFactory = okHttpClient;
options.webSocketFactory = okHttpClient;
}
}
The source code changed to the following:
IO.Options options = new IO.Options();
options.transports = new String[]{"websocket"};
options.reconnectionAttempts = 2;
options.reconnectionDelay = 1000;
options.timeout = 500;
options.rememberUpgrade = true;
options.secure = true;
//usage of the class
SocketSSL.set(options);
final Socket socket = IO.socket(socketServerURL, options);
socket.on(Socket.EVENT_CONNECT, args1 -> socket.send("hello..."));
socket.on("connected", objects -> System.out.println("Server connected: " + objects[0].toString()));
socket.on("push_data_event", objects -> System.out.println("Server:" + objects[0].toString()));
socket.on("myBroadcast", objects -> System.out.println("Server:" + objects[0].toString()));
socket.connect();
socket.emit("chanel_name", message);
I have combined client-certificate-with-com-sun-net-httpserver-httpsserver
with simple-java-https-server but I always get the error message
SSL-Peer could not be verified.
I call setWantClientAuth(true) and verify Authentification by calling
Certificate[] peerCerts = pHttpsExchange.getSSLSession().getPeerCertificates();
The server is running with JDK 1.8 and the client is running on Android. The server Code is:
package de.org.vnetz;
import java.io.*;
import java.net.InetSocketAddress;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.TrustManagerFactory;
import com.sun.net.httpserver.*;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
import javax.net.ssl.SSLContext;
import javax.security.auth.x500.X500Principal;
import java.security.cert.Certificate;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class clsHTTPSServer {
final static String SERVER_PWD = "xxxxxx";
final static String KST_SERVER = "server.jks";
final static String TST_SERVER = "servertrust.jks";
private static final int PORT = 9999;
public static class MyHandler implements HttpHandler {
// whether to use client cert authentication
private final boolean useClientCertAuth = true;
private List<LdapName> allowedPrincipals = new ArrayList<LdapName>();
private final boolean extendedClientCheck = true;
private static final String CLIENTAUTH_OID = "1.3.6.1.5.5.7.3.2";
#Override
public void handle(HttpExchange t) throws IOException {
String response = "Hallo Natalie!";
HttpsExchange httpsExchange = (HttpsExchange) t;
boolean auth;
try
{
checkAuthentication(httpsExchange);
auth = true;
}
catch (Exception ex)
{
response = ex.getMessage();
auth = false;
}
boolean res = httpsExchange.getSSLSession().isValid();
if (res) {
String qry = httpsExchange.getRequestURI().getQuery();
if (qry!=null && qry.startsWith("qry=")) {
httpsExchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
httpsExchange.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
else
{
httpsExchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
httpsExchange.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write((response + " no query!").getBytes());
os.close();
}
}
}
// Verify https certs if its Https request and we have SSL auth enabled. Will be called before
// handling the request
protected void checkAuthentication(HttpExchange pHttpExchange) throws SecurityException {
// Cast will always work since this handler is only used for Http
HttpsExchange httpsExchange = (HttpsExchange) pHttpExchange;
if (useClientCertAuth) {
checkCertForClientUsage(httpsExchange);
checkCertForAllowedPrincipals(httpsExchange);
}
}
// Check the cert's principal against the list of given allowedPrincipals.
// If no allowedPrincipals are given than every principal is allowed.
// If an empty list as allowedPrincipals is given, no one is allowed to access
private void checkCertForClientUsage(HttpsExchange pHttpsExchange) {
try {
String host = pHttpsExchange.getSSLSession().getPeerHost();
//Principal p = pHttpsExchange.getSSLSession().getPeerPrincipal();
String pr = pHttpsExchange.getSSLSession().getProtocol();
Certificate[] peerCerts = pHttpsExchange.getSSLSession().getPeerCertificates();
if (peerCerts != null && peerCerts.length > 0) {
X509Certificate clientCert = (X509Certificate) peerCerts[0];
// We required that the extended key usage must be present if we are using
// client cert authentication
if (extendedClientCheck &&
(clientCert.getExtendedKeyUsage() == null || !clientCert.getExtendedKeyUsage().contains(CLIENTAUTH_OID))) {
throw new SecurityException("No extended key usage available");
}
}
} catch (ClassCastException e) {
throw new SecurityException("No X509 client certificate");
} catch (CertificateParsingException e) {
throw new SecurityException("Can't parse client cert");
} catch (SSLPeerUnverifiedException e) {
throw new SecurityException("SSL Peer couldn't be verified");
}
}
private void checkCertForAllowedPrincipals(HttpsExchange pHttpsExchange) {
if (allowedPrincipals != null) {
X500Principal certPrincipal;
try {
certPrincipal = (X500Principal) pHttpsExchange.getSSLSession().getPeerPrincipal();
Set<Rdn> certPrincipalRdns = getPrincipalRdns(certPrincipal);
for (LdapName principal : allowedPrincipals) {
for (Rdn rdn : principal.getRdns()) {
if (!certPrincipalRdns.contains(rdn)) {
throw new SecurityException("Principal " + certPrincipal + " not allowed");
}
}
}
} catch (SSLPeerUnverifiedException e) {
throw new SecurityException("SSLPeer unverified");
} catch (ClassCastException e) {
throw new SecurityException("Internal: Invalid Principal class provided " + e);
}
}
}
private Set<Rdn> getPrincipalRdns(X500Principal principal) {
try {
LdapName certAsLdapName =new LdapName(principal.getName());
return new HashSet<Rdn>(certAsLdapName.getRdns());
} catch (InvalidNameException e) {
throw new SecurityException("Cannot parse '" + principal + "' as LDAP name");
}
}
}
/**
* #param args
*/
public static void main(String[] args) throws Exception {
try {
// setup the socket address
InetSocketAddress address = new InetSocketAddress(PORT);
// initialise the HTTPS server
HttpsServer httpsServer = HttpsServer.create(address, 0);
SSLContext sslContext = SSLContext.getInstance("TLS");
// initialise the keystore
// char[] password = "password".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream fis = new FileInputStream(KST_SERVER);// ("testkey.jks");
ks.load(fis, SERVER_PWD.toCharArray());// password);
// setup the key manager factory
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, SERVER_PWD.toCharArray());
// setup the trust manager factory
// TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
// tmf.init(ks);
KeyStore ts = KeyStore.getInstance("JKS");
ts.load(new FileInputStream(TST_SERVER), SERVER_PWD.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ts);
// setup the HTTPS context and parameters
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
SSLParameters sslp = sslContext.getSupportedSSLParameters();
//sslp.setNeedClientAuth(true);
sslp.setWantClientAuth(true);
httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext) {
public void configure(HttpsParameters params) {
try {
// initialise the SSL context
SSLContext c = SSLContext.getDefault();
SSLEngine engine = c.createSSLEngine();
//params.setNeedClientAuth(true);
params.setWantClientAuth(true);
params.setCipherSuites(engine.getEnabledCipherSuites());
params.setProtocols(engine.getEnabledProtocols());
// get the default parameters
SSLParameters defaultSSLParameters = c.getDefaultSSLParameters();
SSLParameters sslParams = sslContext.getDefaultSSLParameters();
//sslParams.setNeedClientAuth(true);
sslParams.setWantClientAuth(true);
params.setSSLParameters(defaultSSLParameters);
} catch (Exception ex) {
System.out.println("Failed to create HTTPS port");
}
}
});
httpsServer.createContext("/test", new MyHandler());
httpsServer.setExecutor(
new ThreadPoolExecutor(4, 80, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1000))); // creates
// a
// default
// executor
httpsServer.start();
} catch (Exception exception) {
System.out.println("Failed to create HTTPS server on port " + 62112 + " of localhost");
exception.printStackTrace();
}
}
}
The client code is:
package vnetz.de.org.vnetz;
import android.content.Context;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.SocketException;
import java.net.URL;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
public class clsHTTPS {
private static final String MYURL = "https://localhost:9999/test?qry=test";
static String NO_KEYSTORE = "";
static String UNAUTH_KEYSTORE = "unauthclient.bks"; // Doesn't exist in server trust store, should fail authentication.
static String AUTH_KEYSTORE = "authclient.bks"; // Exists in server trust store, should pass authentication.
static String TRUSTSTORE = "clienttrust.bks";
static String CLIENT_PWD = "xxxxxx";
private static Context context = null;
public clsHTTPS(Context context) {
this.context = context;
}
public static void main(String[] args) throws Exception {
}
public String connect(String jksFile) {
try {
String https_url = MYURL;
URL url;
url = new URL(https_url);
HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(getSSLFactory(jksFile));
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setUseCaches(false);
// Print response
//SSLContext context = SSLContext.getInstance("TLS");
//context.init(null, new X509TrustManager[]{new NullX509TrustManager()}, new SecureRandom());
//HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
BufferedReader bir = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sbline = new StringBuilder();
String line;
while ((line = bir.readLine()) != null) {
System.out.println(line);
sbline.append(line);
}
bir.close();
conn.disconnect();
return sbline.toString();
} catch (SSLHandshakeException | SocketException e) {
System.out.println(e.getMessage());
System.out.println("");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static SSLSocketFactory getSSLFactory(String jksFile) throws Exception {
// Create key store
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
KeyManager[] kmfs = null;
if (jksFile.length() > 0) {
keyStore.load(context.getAssets().open(jksFile), CLIENT_PWD.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, CLIENT_PWD.toCharArray());
kmfs = kmf.getKeyManagers();
}
// create trust store (validates the self-signed server!)
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(context.getAssets().open(TRUSTSTORE), CLIENT_PWD.toCharArray());
TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
trustFactory.init(trustStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmfs, trustFactory.getTrustManagers(), null);
return sslContext.getSocketFactory();
}
private class NullHostNameVerifier implements HostnameVerifier
{
#Override
public boolean verify(String s, SSLSession sslSession)
{
return s.equalsIgnoreCase("localhost");
}
}
private class NullX509TrustManager implements X509TrustManager
{
#Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException
{
}
#Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException
{
}
#Override
public X509Certificate[] getAcceptedIssuers()
{
return new X509Certificate[0];
}
}
}
'Peer not verified' in a server means that the client didn't send a certificate, which probably means that its signer isn't in your server's truststore. When the server requests the client certificate, it supplies a list of acceptable signers, and the client must not send a certificate that isn't signed by one of those.
Or else the server didn't ask for a client certificate at all. Doesn't apply in this case.
In your case it would be a lot simpler to use needClientAuth, as that will just fail the handshake without you having to get as a far as getPeerCertificates().
NB:
The SSLSession is valid, otherwise you wouldn't have an SSL connection. The only way it becomes invalid is if you call invalidate(), which causes a full re-handshake on the next I/O. You're testing the wrong thing.
Checking for allowed principals is authorization, not authentication.
I am using a rest service which requires authentication, Below curl command is used to achieve this
curl -v --insecure --request POST "https://ip:port/login" -d IDToken1="username" -d "password" --cookie-jar cookie.txt
After authentication it creates a cookie file.
Can someone helps in creating the corresponding rest client using java.
I have used
ClientConfig config = new ClientConfig();
Client client = ClientBuilder.newClient(config);
WebTarget target = client
.target("http://hilweb05:8080/login");
Form form = new Form().param("IDToken1", "username").param("IDToken2", "password");
Response jsonAnswer = target.request()
.accept(MediaType.APPLICATION_JSON).post(Entity.form(form));
if (jsonAnswer.getStatus() != 200) {
throw new RuntimeException("Not reachable "
+ jsonAnswer.getStatus());
}
List<SomeDataClass> matList = jsonAnswer.readEntity(new GenericType<List<SomeDataClass>>() {});
for (SomeDataClass m : matList) {
System.out.println(m.getF1() + " " + m.getF2() + " "
+ m.getF3());
}
But its not working
I switched to Apache http client, with the below piece of code I am able to get the cookie.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.net.ssl.SSLContext;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
public class ApacheHttpClient {
public static void main(String[] args) throws ClientProtocolException, IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial((chain, authType) -> true).build();
SSLConnectionSocketFactory sslConnectionSocketFactory =
new SSLConnectionSocketFactory(sslContext, new String[]
{"SSLv2Hello", "SSLv3", "TLSv1","TLSv1.1", "TLSv1.2" }, null,
NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(sslConnectionSocketFactory)
.build();
try {
HttpPost httpPost = new HttpPost("url/login");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("IDToken1", name));
nvps.add(new BasicNameValuePair("IDToken2", password));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response2 = httpclient.execute(httpPost);
try {
System.out.println("Status -->>> "+ response2.getStatusLine().getStatusCode());
Header[] cookieInf = response2.getHeaders("Set-Cookie");
StringBuilder strBf = new StringBuilder();
for(Header header : cookieInf)
{
strBf.append(header.getValue());
}
System.out.println("Data is "+ strBf);
HttpEntity entity2 = response2.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} finally {
response2.close();
}
} finally {
httpclient.close();
}
}
}
Now I need to write the cookie in a text file, so I need help in parsing the cookie information so that it matches the cookie file generated by curl command.
With the below piece of code it works
public class JerseyClientPost {
public static void main(String[] args) {
try {
Client client = Client.create(configureClient());
final com.sun.jersey.api.client.WebResource webResource = client
.resource("https://wtc2e3enm.eng.mobilephone.net:443/login");
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("IDToken1", name);
formData.add("IDToken2", password);
try {
ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED)
.accept(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, formData);
String x = response.getEntity(String.class);
System.out.println("Response String is "+ x);
} catch (com.sun.jersey.api.client.ClientHandlerException che) {
che.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static ClientConfig configureClient() {
TrustManager[] certs = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
} };
SSLContext ctx = null;
try {
ctx = SSLContext.getInstance("SSL");
ctx.init(null, certs, new SecureRandom());
} catch (java.security.GeneralSecurityException ex) {
}
HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
ClientConfig config = new DefaultClientConfig();
try {
config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
new HTTPSProperties(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}, ctx));
} catch (Exception e) {
}
return config;
}
}
but I am not able to get the cookies from response, if I use curl I am able to get the cookie by using --cookie-jar argument. Can somebody help in getting the cookie
I used httpclient 4.4 to send get and post request. and i just created a simpile wrapper of httpclient for easy use:
package com.u8.server.sdk;
import com.sun.net.httpserver.Headers;
import com.u8.server.log.Log;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.CookiePolicy;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Created by ant on 2015/10/12.
*/
public class UHttpAgent {
private int connectTimeout = 5000; //5s
private int socketTimeout = 5000; //5s
private int maxTotalConnections = 200;
private static UHttpAgent instance;
private CloseableHttpClient httpClient;
private UHttpAgent(){
}
public static UHttpAgent getInstance(){
if(instance == null){
instance = new UHttpAgent();
}
return instance;
}
public static UHttpAgent newInstance(){
return new UHttpAgent();
}
public String get(String url, Map params){
return get(url, null, params, "UTF-8");
}
public String post(String url, Map params){
return post(url, null, params, "UTF-8");
}
public String get(String url , Map headers, Map params, String encoding){
if(this.httpClient == null){
init();
}
String fullUrl = url;
String urlParams = parseGetParams(params, encoding);
if (urlParams != null)
{
if (url.contains("?"))
{
fullUrl = url + "&" + urlParams;
}
else
{
fullUrl = url + "?" + urlParams;
}
}
Log.d("the full url is "+ fullUrl);
HttpGet getReq = new HttpGet(fullUrl.trim());
getReq.setHeaders(parseHeaders(headers));
ResponseHandler responseHandler = new ResponseHandler() {
#Override
public String handleResponse(HttpResponse httpResponse) throws IOException {
HttpEntity entity = httpResponse.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
}
};
try {
String res = httpClient.execute(getReq, responseHandler);
return res;
} catch (Exception e) {
e.printStackTrace();
}finally {
getReq.releaseConnection();
}
return null;
}
public String post(String url, Map headers, Map params, String encoding){
List pairs = new ArrayList();
if(params != null){
for(String key : params.keySet()){
pairs.add(new BasicNameValuePair(key, params.get(key)));
}
}
return post(url, headers, new UrlEncodedFormEntity(pairs, Charset.forName(encoding)));
}
public String post(String url, Map headers, HttpEntity entity){
if(this.httpClient == null) {
init();
}
HttpPost httpPost = new HttpPost(url);
httpPost.setHeaders(parseHeaders(headers));
httpPost.setEntity(entity);
ResponseHandler responseHandler = new ResponseHandler() {
#Override
public String handleResponse(HttpResponse httpResponse) throws IOException {
HttpEntity entity = httpResponse.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
}
};
try {
String body = httpClient.execute(httpPost, responseHandler);
return body;
} catch (IOException e) {
e.printStackTrace();
}finally {
httpPost.releaseConnection();
}
return null;
}
private Header[] parseHeaders(Map headers){
if(null == headers || headers.isEmpty()){
return getDefaultHeaders();
}
Header[] hs = new BasicHeader[headers.size()];
int i = 0;
for(String key : headers.keySet()){
hs[i] = new BasicHeader(key, headers.get(key));
i++;
}
return hs;
}
private Header[] getDefaultHeaders(){
Header[] hs = new BasicHeader[2];
hs[0] = new BasicHeader("Content-Type", "application/x-www-form-urlencoded");
hs[1] = new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
return hs;
}
private String parseGetParams(Map data, String encoding){
if(data == null || data.size() keyItor = data.keySet().iterator();
while(keyItor.hasNext()){
String key = keyItor.next();
String val = data.get(key);
try {
result.append(key).append("=").append(URLEncoder.encode(val, encoding).replace("+", "%2B")).append("&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return result.deleteCharAt(result.length() - 1).toString();
}
private void init(){
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setSocketTimeout(socketTimeout)
.setExpectContinueEnabled(true)
.setAuthenticationEnabled(true)
.build();
HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {
#Override
public boolean retryRequest(IOException e, int retryNum, HttpContext httpContext) {
if(retryNum >= 3){
return false;
}
if(e instanceof org.apache.http.NoHttpResponseException
|| e instanceof org.apache.http.client.ClientProtocolException
|| e instanceof java.net.SocketException){
return true;
}
return false;
}
};
try{
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
#Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
Registry socketFactoryRegistry = RegistryBuilder.create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslFactory)
.build();
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager( socketFactoryRegistry);
connMgr.setMaxTotal(maxTotalConnections);
connMgr.setDefaultMaxPerRoute((connMgr.getMaxTotal()));
HttpClientBuilder builder = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setSslcontext(sslContext)
.setConnectionManager(connMgr)
.setRetryHandler(retryHandler);
this.httpClient = builder.build();
}catch (Exception e){
e.printStackTrace();
}
}
public HttpClient getHttpClient(){
return this.httpClient;
}
public void destroy(){
if(this.httpClient != null){
try{
this.httpClient.close();
this.httpClient = null;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
when I use this class to send post request. something strange happened:
the first time, I send a post request to the server, it's ok
after a minutes, I send a same request to the server, it's ok too.
but after a few minutes, I send a same request, something wrong:
java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
at org.apache.http.impl.conn.LoggingOutputStream.write(LoggingOutputStream.java:77)
at org.apache.http.impl.io.SessionOutputBufferImpl.streamWrite(SessionOutputBufferImpl.java:126)
at org.apache.http.impl.io.SessionOutputBufferImpl.flushBuffer(SessionOutputBufferImpl.java:138)
at org.apache.http.impl.io.SessionOutputBufferImpl.flush(SessionOutputBufferImpl.java:146)
at org.apache.http.impl.BHttpConnectionBase.doFlush(BHttpConnectionBase.java:175)
at org.apache.http.impl.DefaultBHttpClientConnection.flush(DefaultBHttpClientConnection.java:185)
at org.apache.http.impl.conn.CPoolProxy.flush(CPoolProxy.java:177)
at org.apache.http.protocol.HttpRequestExecutor.doSendRequest(HttpRequestExecutor.java:215)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:122)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:271)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:71)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:220)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:164)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:139)
at com.u8.server.sdk.UHttpAgent.post(UHttpAgent.java:259)
at com.u8.server.sdk.UHttpAgent.post(UHttpAgent.java:147)
at com.u8.server.sdk.baidu.BaiduSDK.verify(BaiduSDK.java:30)
at com.u8.server.web.UserAction.getLoginToken(UserAction.java:100)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
but then , I still send a same request to the server, it's ok again.
Every time I tried according to the above steps, The same thing happened.
Anyone can help me ? Thanks a lot.
The peer of your client is the server. So "Connection reset by peer" means the server reset the socket. Reset means forceably closed.
This might be because of a bug in the server. If you also wrote the server or servlet (as will be the case for a custom protocol), you need to examine the behaviour of the server to examine the cause of this. The log files of the server might provide clues.
If the server has protection against bisbehaving or malicious clients, the server might have reset the socket because it has classified your client as misbehaving. If you implemented the client protocol code it might be because of a bug in your protocol implementation. If you are using third party code for handling the communication protocol you might still be misusing it; for example by sending excessively large requests. It is not uncommon for HTTP servers to protect themselves against denial of service attacks by imposing maximum lengths for header fields and bodies, and to require that clients send data at a reasonably fast rate (without pausing for long periods). Your client might have fallen foul of these protections.
Is there a way for the standard java SSL sockets to disable hostname verfication for ssl connections with a property? The only way I found until now, is to write a hostname verifier which returns true all the time.
Weblogic provides this possibility, it is possible to disable the hostname verification with the following property:
-Dweblogic.security.SSL.ignoreHostnameVerify
It should be possible to create custom java agent that overrides default HostnameVerifier:
import javax.net.ssl.*;
import java.lang.instrument.Instrumentation;
public class LenientHostnameVerifierAgent {
public static void premain(String args, Instrumentation inst) {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
}
}
Then just add -javaagent:LenientHostnameVerifierAgent.jar to program's java startup arguments.
The answer from #Nani doesn't work anymore with Java 1.8u181. You still need to use your own TrustManager, but it needs to be a X509ExtendedTrustManager instead of a X509TrustManager:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509ExtendedTrustManager;
public class Test {
public static void main (String [] args) throws IOException {
// This URL has a certificate with a wrong name
URL url = new URL ("https://wrong.host.badssl.com/");
try {
// opening a connection will fail
url.openConnection ().connect ();
} catch (SSLHandshakeException e) {
System.out.println ("Couldn't open connection: " + e.getMessage ());
}
// Bypassing the SSL verification to execute our code successfully
disableSSLVerification ();
// now we can open the connection
url.openConnection ().connect ();
System.out.println ("successfully opened connection to " + url + ": " + ((HttpURLConnection) url.openConnection ()).getResponseCode ());
}
// Method used for bypassing SSL verification
public static void disableSSLVerification () {
TrustManager [] trustAllCerts = new TrustManager [] {new X509ExtendedTrustManager () {
#Override
public void checkClientTrusted (X509Certificate [] chain, String authType, Socket socket) {
}
#Override
public void checkServerTrusted (X509Certificate [] chain, String authType, Socket socket) {
}
#Override
public void checkClientTrusted (X509Certificate [] chain, String authType, SSLEngine engine) {
}
#Override
public void checkServerTrusted (X509Certificate [] chain, String authType, SSLEngine engine) {
}
#Override
public java.security.cert.X509Certificate [] getAcceptedIssuers () {
return null;
}
#Override
public void checkClientTrusted (X509Certificate [] certs, String authType) {
}
#Override
public void checkServerTrusted (X509Certificate [] certs, String authType) {
}
}};
SSLContext sc = null;
try {
sc = SSLContext.getInstance ("SSL");
sc.init (null, trustAllCerts, new java.security.SecureRandom ());
} catch (KeyManagementException | NoSuchAlgorithmException e) {
e.printStackTrace ();
}
HttpsURLConnection.setDefaultSSLSocketFactory (sc.getSocketFactory ());
}
}
There is no hostname verification in standard Java SSL sockets or indeed SSL, so that's why you can't set it at that level. Hostname verification is part of HTTPS (RFC 2818): that's why it manifests itself as javax.net.ssl.HostnameVerifier, which is applied to an HttpsURLConnection.
I also had the same problem while accessing RESTful web services. And I their with the below code to overcome the issue:
public class Test {
//Bypassing the SSL verification to execute our code successfully
static {
disableSSLVerification();
}
public static void main(String[] args) {
//Access HTTPS URL and do something
}
//Method used for bypassing SSL verification
public static void disableSSLVerification() {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
SSLContext sc = null;
try {
sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
}
It worked for me. try it!!
In case you're using apache's http-client 4:
SSLConnectionSocketFactory sslConnectionSocketFactory =
new SSLConnectionSocketFactory(sslContext,
new String[] { "TLSv1.2" }, null, new HostnameVerifier() {
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
#user207421 is right, there is no hostname verification in standard Java SSL sockets or indeed SSL.
But X509ExtendedTrustManager implement the host name check logic(see it's javadoc). To disable this, We can set SSLParameters .endpointIdentificationAlgorithm to null as JDK AbstractAsyncSSLConnection did:
if (!disableHostnameVerification)
sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); // default is null
disableHostnameVerification is read from property: jdk.internal.httpclient.disableHostnameVerification。
How to modify SSLParameters Object is dependends on the specify soft you use。
as spring webflux WebClient:
HttpClient httpClient = HttpClient.create()
.secure(sslContextSpec ->
sslContextSpec
.sslContext(sslContext)
.handlerConfigurator(sslHandler -> {
SSLEngine engine = sslHandler.engine();
SSLParameters newSslParameters = engine.getSSLParameters(); // 返回的是一个新对象
// 参考:https://github.com/AdoptOpenJDK/openjdk-jdk11/blob/master/src/java.net.http/share/classes/jdk/internal/net/http/AbstractAsyncSSLConnection.java#L116
newSslParameters.setEndpointIdentificationAlgorithm(null);
engine.setSSLParameters(newSslParameters);
})
)
WebClient webclient = WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(httpClient))
.build();