Jetty Java websocket client doesn't connect to server - eclipse

I am using Java Jetty client written [websocket-client 9.3.8.RC0]. Websocket server is little wierd in our case.
It accepting request in format.
wss://192.168.122.1:8443/status?-xsrf-=tokenValue
Token Value is received in first Login POST request in which i get Token Value & Cookie header. Cookie is added as a header whereas token is given as a param.
Now question is : -
When i run below code it just call awaitclose() function in starting. But there is not other function called i.e. Onconnected or even Onclose.
Any help would be appreciated to debug it further, to see any logs or environment issue to see why Socket is not connected.
Trying to figure out following points to debug.
1. To check if client certificates are causing issue.
Tried with my python code wspy.py it work seemlessly fine.
Code is
public final class websocketxxx {
WebSocketClient client=null;
public websocketxxx (){
}
public void run(String host,String cookieVal, String xsrfVal, String resource) throws IOException {
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setTrustAll(true);
WebSocketClient client = new WebSocketClient(sslContextFactory);
MyWebSocket socket = new MyWebSocket();
try {
client.start();
ClientUpgradeRequest request = new ClientUpgradeRequest();
// Add the authentication and protocol to the request header
// Crate wss URI from host and resource
resource = resource + xsrfVal;
URI destinationUri = new URI("wss://" + host + resource); // set URI
request.setHeader("cookie",cookieVal);
request.setHeader("Sec-WebSocket-Protocol", "ao-json");
//System.out.println("Request Headers print : " request.getHeaders())
System.out.println("Connecting to : " + destinationUri);
client.connect(socket, destinationUri, request);
socket.awaitClose(5000, TimeUnit.SECONDS);
} catch (Throwable t) {
t.printStackTrace();
} finally {
try {
client.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#WebSocket
public class MyWebSocket {
private final CountDownLatch closeLatch = new CountDownLatch(1);
#OnWebSocketConnect
public void onConnect(Session session) {
System.out.println("WebSocket Opened in client side");
try {
System.out.println("Sending message: Hi server");
session.getRemote().sendString("Hi Server");
} catch (IOException e) {
e.printStackTrace();
}
}
#OnWebSocketMessage
public void onMessage(String message) {
System.out.println("Message from Server: " + message);
}
#OnWebSocketClose
public void onClose(int statusCode, String reason) {
System.out.println("WebSocket Closed. Code:" + statusCode);
}
public boolean awaitClose(int duration, TimeUnit unit) throws InterruptedException {
return this.closeLatch.await(duration, unit);
}
}
public Client getBypassCertVerificationClient() {
Client client1 = null;
try {
// Create a HostnameVerifier that overrides the verify method to accept all hosts
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
public boolean verify(String host, SSLSession sslSession) {
return true;
}
};
// Create a TrustManager
TrustManager[] trust_mgr = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String t) {
}
public void checkServerTrusted(X509Certificate[] certs, String t) {
}
}
};
// Create the SSL Context
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trust_mgr, new SecureRandom());
// Create the client with the new hostname verifier and SSL context
client1 = ClientBuilder.newBuilder()
.sslContext(sslContext)
.hostnameVerifier(hostnameVerifier)
.build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return client1;
}
public String[] simple_Login_POST_request(String host, String user, String password, String resource, String data) {
String resp = null;
String[] headers = new String[2];
try {
// Create a Client instance that supports self-signed SSL certificates
Client client = getBypassCertVerificationClient();
// Create a WebTarget instance with host and resource
WebTarget target = client.target("https://" + host).path(resource);
// Build HTTP request invocation
Invocation.Builder invocationBuilder = target.request();
// Encode the user/password and add it to the request header
invocationBuilder.header(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
Form form = new Form();
form.param("userid", user);
form.param("password", password);
// Invoke POST request and get response as String
//post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE));
Response response = invocationBuilder.method("POST", Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE));
resp = (String) response.readEntity(String.class);
// Print input URL, input data, response code and response
System.out.println("URL: [POST] " + target.getUri().toString());
System.out.println("HTTP Status: " + response.getStatus());
System.out.println("HTTP Status: " + response.getHeaders());
headers[0] = response.getHeaderString("Set-Cookie");
//response.getStringHeaders()
headers[1] = response.getHeaderString("X-XSRF-TOKEN");
System.out.println("Response: \n" + resp);
response.close();
} catch (Exception e) {
e.printStackTrace();
}
return headers;
}
public static void main(String[] args) throws IOException {
String host = "";
String user = "";
String password = "";
String resource = "";
host ="192.168.122.1:8443";
user = "ADMIN";
password ="ADMIN";
websocketXXX wsNotification = new websocketxxx();
/////////////////////////////////////////////////////////////////
// Simple POST LOGIN Request
resource = "/api/login";
String headers[]= wsNotification.simple_Login_POST_request(host, user, password, resource, null);
////////////////////////////////////////////////////////////////
headers[0] = headers[0].substring(headers[0].lastIndexOf(",") + 1);
System.out.println("headers[0]: " + headers[0] + "\n");
String cookie = headers[0];
String XSRFToken = headers[1];
resource = "/status?-xsrf-=";
//wsNotification.simple_websocket_example(host, cookie, XSRFToken, resource);
wsNotification.run(host, cookie, XSRFToken, resource);
}
}

The implementation is mostly correct.
Setting raw Cookie and Sec-WebSocket-* headers is forbidden, you have to use the API.
Cookie handling from:
ClientUpgradeRequest request = new ClientUpgradeRequest();
request.setHeader("cookie",cookieVal);
To ClientUpgradeRequest.setCookies() :
ClientUpgradeRequest request = new ClientUpgradeRequest();
List<HttpCookie> cookies = new ArrayList<>();
cookies.add(new HttpCookie(...));
request.setCookies(cookies);
Note: if you are using the java CookieStore, then you can pass the CookieStore instance to the client as well, using the setCookiesFrom(CookieStore) method.
Sub Protocol Selection from:
ClientUpgradeRequest request = new ClientUpgradeRequest();
request.setHeader("Sec-WebSocket-Protocol", "ao-json");
To ClientUpgradeRequest.setSubProtocols():
ClientUpgradeRequest request = new ClientUpgradeRequest();
request.setSubProtocols("ao-json");

Related

Created OAuth bearer token generated with jwt token is invalid for REST calls

I am new to DocuSign and the REST-API. I created a developer account and added a new "Apps and Keys" entry for my application (Authentication = Implicit Grant and RSA key pairs). The keys were stored in two seperate files.
I activated the Keys using the following URL:
http://account-d.docusign.com/oauth/auth?response_type=code&scope=signature%20impersonation&client_id=_the_integration_key&redirect_uri=http://localhost
I am trying to write a JAVA application without spring security framework (or any other framework).
To read the key files I used and modified (a little bit) the functions from the DocuSign examples.
private static RSAPublicKey readPublicKeyFromFile(String filepath, String algorithm) throws IOException {
File pemFile = new File(filepath);
if (!pemFile.isFile() || !pemFile.exists()) {
throw new FileNotFoundException(String.format("The file '%s' doesn't exist.", pemFile.getAbsolutePath()));
}
PemReader reader = new PemReader(new FileReader(pemFile));
try {
PemObject pemObject = reader.readPemObject();
byte[] bytes = pemObject.getContent();
RSAPublicKey publicKey = null;
try {
KeyFactory kf = KeyFactory.getInstance(algorithm);
EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
publicKey = (RSAPublicKey) kf.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
System.out.println("Could not reconstruct the public key, the given algorithm could not be found.");
} catch (InvalidKeySpecException e) {
System.out.println("Could not reconstruct the public key");
}
return publicKey;
} finally {
reader.close();
}
}
private static RSAPrivateKey readPrivateKeyFromFile(String filepath, String algorithm) throws IOException {
File pemFile = new File(filepath);
if (!pemFile.isFile() || !pemFile.exists()) {
throw new FileNotFoundException(String.format("The file '%s' doesn't exist.", pemFile.getAbsolutePath()));
}
PemReader reader = new PemReader(new FileReader(pemFile));
try {
PemObject pemObject = reader.readPemObject();
byte[] bytes = pemObject.getContent();
RSAPrivateKey privateKey = null;
try {
Security.addProvider(new BouncyCastleProvider());
KeyFactory kf = KeyFactory.getInstance(algorithm, "BC");
EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
privateKey = (RSAPrivateKey) kf.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
System.out.println("Could not reconstruct the private key, the given algorithm could not be found.");
} catch (InvalidKeySpecException e) {
System.out.println("Could not reconstruct the private key");
} catch (NoSuchProviderException e) {
System.out.println("Could not reconstruct the private key, invalid provider.");
}
return privateKey;
} finally {
reader.close();
}
}
private static RSAPrivateKey readPrivateKeyFromByteArray(byte[] privateKeyBytes, String algorithm) throws IOException {
PemReader reader = new PemReader(new StringReader(new String(privateKeyBytes)));
try {
PemObject pemObject = reader.readPemObject();
byte[] bytes = pemObject.getContent();
RSAPrivateKey privateKey = null;
try {
Security.addProvider(new BouncyCastleProvider());
KeyFactory kf = KeyFactory.getInstance(algorithm, "BC");
EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
privateKey = (RSAPrivateKey) kf.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
System.out.println("Could not reconstruct the private key, the given algorithm could not be found.");
} catch (InvalidKeySpecException e) {
System.out.println("Could not reconstruct the private key");
} catch (NoSuchProviderException e) {
System.out.println("Could not reconstruct the private key, invalid provider.");
}
return privateKey;
} finally {
reader.close();
}
}
To get the JWT token I used the following function:
public static String generateJWTAssertion(String publicKeyFilename, String privateKeyFilename, String oAuthBasePath, String clientId, String userId, long expiresIn) throws JWTCreationException, IOException {
String token = null;
if (expiresIn <= 0L) {
throw new IllegalArgumentException("expiresIn should be a non-negative value");
}
if (publicKeyFilename == null || "".equals(publicKeyFilename) || privateKeyFilename == null || "".equals(privateKeyFilename) || oAuthBasePath == null || "".equals(oAuthBasePath) || clientId == null || "".equals(clientId)) {
throw new IllegalArgumentException("One of the arguments is null or empty");
}
try {
RSAPublicKey publicKey = readPublicKeyFromFile(publicKeyFilename, "RSA");
RSAPrivateKey privateKey = readPrivateKeyFromFile(privateKeyFilename, "RSA");
Algorithm algorithm = Algorithm.RSA256(publicKey, privateKey);
long now = System.currentTimeMillis();
token = JWT.create()
.withIssuer(clientId) // integration key
.withSubject(userId) // null
.withAudience(oAuthBasePath) // account-d.docusign.com
.withNotBefore(new Date(now))
.withExpiresAt(new Date(now + expiresIn * 1000))
.withClaim("scope", "signature impersonation")
.sign(algorithm);
} catch (JWTCreationException e){
throw e;
} catch (IOException e) {
throw e;
}
return token;
}
I checked the generated token on https://jwt.io/ and the content looks fine.
To get the bearer token I use the following code:
public Boolean getBearer(long expiresIn) throws IOException {
String jwtToken = JwtUtils.generateJWTAssertion(
RESOURCES_DIR + "public.key",
RESOURCES_DIR + "private.key",
oAuthBasePath,
integrationKey,
null,
expiresIn
);
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer")
.addFormDataPart("assertion", jwtToken)
.build();
Request request = new Request.Builder()
.url("https://" + oAuthBasePath + "/oauth/token") // https://account-d.docusign.com/oauth/token
.method("POST", body)
.build();
Response response = client.newCall(request).execute();
int responseCode = response.code();
String responseText = response.body().string();
Gson gson = new Gson();
OAuthResponse oAuthResponse = gson.fromJson(responseText, OAuthResponse.class);
if (responseCode >= 200 && responseCode <= 299) {
bearerToken = oAuthResponse.getAccess_token();
return true;
}
System.out.println("Errorcode: " + oAuthResponse.getError());
System.out.println("Error: " + oAuthResponse.getError_description());
return false;
}
I get the bearer token and want to use it for the following REST calls.
For example:
public void getUsers () throws IOException {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
Request request = new Request.Builder()
.url(getRestBaseUrl() +"/users") // https://demo.docusign.net/restapi/v2.1/accounts/_API_account_id/users
.method("GET", null)
.addHeader("Accept", "application/json")
.addHeader("Authorization", "Bearer " + bearerToken)
.build();
Response response = client.newCall(request).execute();
String responseText = response.body().string();
System.out.println(responseText);
}
But instead of a JSON structure with the users of my developer account, I got the following response:
{"errorCode":"AUTHORIZATION_INVALID_TOKEN","message":"The access token provided is expired, revoked or malformed. Authentication for System Application failed."}
When I use the API explorer and the bearer token, I can use it for authentication (it is shown as valid), but the REST call for "users" get the same error response.
So I used the API explorer for login and the REST call works.
I used the bearer token from the API explorer and used it (as fixed entered string value) as bearer token. And the JAVA REST calls works.
So, there must be an error in generating / requesting the JWT token or bearer token.
Any idea what's wrong?
Regards,
Rainer
I found the reason.
The API username was missing.
String jwtToken = JwtUtils.generateJWTAssertion(
RESOURCES_DIR + "public.key",
RESOURCES_DIR + "private.key",
oAuthBasePath,
integrationKey,
"_here_the_API_username",
expiresIn
);
After adding the username I could use the API.

Netty connection pool not sending messages to server

I have a simple netty connection pool and a simple HTTP endpoint to use that pool to send TCP messages to ServerSocket. The relevant code looks like this, the client (NettyConnectionPoolClientApplication) is:
#SpringBootApplication
#RestController
public class NettyConnectionPoolClientApplication {
private SimpleChannelPool simpleChannelPool;
public static void main(String[] args) {
SpringApplication.run(NettyConnectionPoolClientApplication.class, args);
}
#PostConstruct
public void setup() throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group);
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.remoteAddress(new InetSocketAddress("localhost", 9000));
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(new DummyClientHandler());
}
});
simpleChannelPool = new SimpleChannelPool(bootstrap, new DummyChannelPoolHandler());
}
#RequestMapping("/test/{msg}")
public void test(#PathVariable String msg) throws Exception {
Future<Channel> future = simpleChannelPool.acquire();
future.addListener((FutureListener<Channel>) f -> {
if (f.isSuccess()) {
System.out.println("Connected");
Channel ch = f.getNow();
ch.writeAndFlush(msg + System.lineSeparator());
// Release back to pool
simpleChannelPool.release(ch);
} else {
System.out.println("not successful");
}
});
}
}
and the Server (ServerSocketRunner)
public class ServerSocketRunner {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(9000);
while (true) {
Socket socket = serverSocket.accept();
new Thread(() -> {
System.out.println("New client connected");
try (PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));) {
String inputLine, outputLine;
out.println("Hello client!");
do {
inputLine = in.readLine();
System.out.println("Received: " + inputLine);
} while (!"bye".equals(inputLine));
System.out.println("Closing connection...");
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
}
DummyChannelPoolHandler and DummyClientHandler just print out events that happen, so they are not relevant. When the server and the client are started and I send a test message to test endpoint, I can see the server prints "New client connected" but the message sent by client is not printed. None of the consecutive messages sent by client are printed by the server.
If I try telnet, everything works fine, the server prints out messages. Also it works fine with regular netty client with same bootstrap config and without connection pool (SimpleNettyClientApplication).
Can anyone see what is wrong with my connection pool, I'm out of ideas
Netty versioin: 4.1.39.Final
All the code is available here.
UPDATE
Following Norman Maurer advice. I added
ChannelFuture channelFuture = ch
.writeAndFlush(msg + System.lineSeparator());
channelFuture.addListener(writeFuture -> {
System.out
.println("isSuccess(): " + channelFuture.isSuccess() + " : " + channelFuture.cause());
});
This prints out
isSuccess: false : java.lang.UnsupportedOperationException: unsupported message type: String (expected: ByteBuf, FileRegion)
To fix it, I just converted String into ByteBuf
ch.writeAndFlush(Unpooled.wrappedBuffer((msg + System.lineSeparator()).getBytes()));
You should check what the status of the ChannelFuture is that is returned by writeAndFlush(...). I suspect it is failed.

Unable to access REST API’s in Camunda

In our project , we are trying to use camunda BPMN. using camunda standalone distro and deployed and running in Tomcat.
login as a admin user and able to access cockpit and task lists.But,when we try access the APIs using a Java client . we are getting an unauthorized (401) error. Though we are sending JSESSIONID as a “Cookie”
Tried both DefaultHttpClient and HttpURLConnection - It didn’t work out
Note : JSESSIONID is retrieved by calling the login api with admin username and password.
Help me to solve the issue
Attached below is the java client code
public static void main(String[] args) {
CamundaBMPNClient bpmnClient = new CamundaBMPNClient();
Map<Integer, String> cookieHeader = bpmnClient.getCookieHeader();
bpmnClient.getListofTasks(cookieHeader);
}
public Map<Integer, String> getCookieHeader() {
String jSessionID = null;
Map<Integer, String> headerValues = new HashMap<Integer, String>();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(
"http://localhost:8090/camunda-webapp-tomcat-standalone-7.2.0/"
+ "api/admin/auth/user/default/login/cockpit");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.addHeader("Accept", "application/json");
String jsonString = new Gson()
.toJson("username=admin&password=admin#123");
StringEntity params;
try {
params = new StringEntity(jsonString);
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
Header[] cookieheader = response.getHeaders("Set-Cookie");
for (Header s : cookieheader) {
// Do your stuff here
System.out.println(s.getValue());
String[] str = s.getValue().split(";");
int i = 1;
for (String s1 : str) {
headerValues.put(i, s1.trim());
i++;
}
}
System.out.println("jSessionID::" + jSessionID);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return headerValues;
}
public void getListofTasks(Map<Integer, String> cookieHeader) {
int id = 0;
// DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(
"http://localhost:8090/camunda-webapp-tomcat-standalone-7.2.0/api/engine/engine/default/task");
request.addHeader("Content-type", "application/json");
String[] arrJSessionID = cookieHeader.get(1).split("=");
System.out.println("" + arrJSessionID[1]);
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID=",
arrJSessionID[1]);
cookie.setDomain("http://localhost:8090");
cookie.setPath("/camunda-webapp-tomcat-standalone-7.2.0/");
// cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");
cookieStore.addCookie(cookie);
// httpclient.setCookieStore(cookieStore);
HttpClient httpclient = HttpClientBuilder.create()
.setDefaultCookieStore(cookieStore).build();
String jsonString = new Gson().toJson("{}");
StringEntity jsonStr;
try {
jsonStr = new StringEntity(jsonString);
request.setEntity(jsonStr);
HttpResponse response = httpclient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
Header[] header = response.getHeaders("Set-Cookie");
for (Header h : header) {
System.out.println(h.getValue());
}
System.out.println("statusCode::" + statusCode);
} catch (Exception e) {
e.printStackTrace();
}
}

How to resolve "Connection Refused" from .NET HttpClient when URL works fine from browser

This is Xamarin app which is accessing the www.geonames.org site. When I run it, it generates a System.Net.WebException "Error: ConnectFailure (Connection refused)". However, if I take the url produced in this method and paste it into a browser on the simulator, it works fine and returns the correct JSON.
public async Task GetWeatherAsync(double longitude, double latitude, string username)
{
var url = string.Format("http://api.geonames.org/findNearByWeatherJSON?lat={0}&lng={1}&username={2}", latitude, longitude, username);
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
try
{
var response = await client.GetAsync(client.BaseAddress);
if (response.IsSuccessStatusCode)
{
var JsonResult = response.Content.ReadAsStringAsync().Result;
var weather = JsonConvert.DeserializeObject<WeatherResult>(JsonResult);
SetValues(weather);
}
else
{
Debug.WriteLine(response.RequestMessage);
}
}
catch (HttpRequestException ex)
{
Debug.WriteLine(ex.Message);
}
catch (System.Net.WebException ex)
{
Debug.WriteLine(ex.Message);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
The solution is to add a HttpClientHandler with the appropriate proxy settings. Instantiate an instance of IWebProxy:
public class WebProxy : IWebProxy
{
public ICredentials Credentials { get; set; }
private readonly Uri _proxyUri;
public WebProxy(string proxyString)
{
_proxyUri = new Uri(proxyString);
}
public WebProxy(Uri proxyUri)
{
_proxyUri = proxyUri;
}
public Uri GetProxy(Uri destination)
{
return _proxyUri;
}
public bool IsBypassed(Uri host)
{
return false;
}
}
Then instantiate the HttpClient with a handler that uses the proxy:
NetworkCredential proxyCreds = new NetworkCredential(
ProxyConfig.Username, ProxyConfig.Password);
WebProxy proxy = new WebProxy(ProxyConfig.Url)
{
Credentials = proxyCreds
};
HttpClientHandler handler = new HttpClientHandler
{
PreAuthenticate = true,
UseDefaultCredentials = false,
Proxy = proxy
};
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri(url);

Use apache httpclient as backend for jersey client base on PoolingHttpClientConnectionManager

i try to use apache httpclient as backend for jersey client to handle cookie automatically and here is my code
class ClientHelper {
public static HttpClientConnectionManager customConnectionManager() throws Exception {
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{new X509TrustManager() {
#Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
throws CertificateException {
System.out.println("========checkClientTrusted=========");
}
#Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
throws CertificateException {
System.out.println("========checkServerTrusted==========");
}
#Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}}, new SecureRandom());
SSLConnectionSocketFactory
sslConnectionSocketFactory =
new SSLConnectionSocketFactory(sslContext);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslConnectionSocketFactory)
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager phcc = new PoolingHttpClientConnectionManager(registry);
return phcc;
}
public static Client createClient() {
HttpClient apacheClient = null;
try {
apacheClient =
HttpClientBuilder.create().setConnectionManager(customConnectionManager()).build();
} catch (Exception e) {
e.printStackTrace();
}
Client client = new Client(new ApacheHttpClient4Handler(apacheClient,
new BasicCookieStore(),
true));
return client;
}
}
I try to use the apache httpclient as the backend of jersey client (in order to handle the cookie)
Then, I create a simple class to test client,
import com.sun.jersey.api.client.Client;
....
public class ApiTest {
private static Client client;
public String getAuth(String username, String passwd) {
Map<String, String> formParams = new HashMap<String, String>();
formParams.put("username", String.valueOf(username));
formParams.put("passwd", String.valueOf(passwd));
try {
String basePath = "https://xyzhost/login";
if (client == null) {
client = ClientHelper.createClient();
client.addFilter(new LoggingFilter(System.out));
}
WebResource webResource = client.resource(basePath);
ClientResponse response = webResource.type("application/x-www-form-urlencoded").accept("application/json")
.post(ClientResponse.class, processFormParams(formParams));
if (response != null) {
String authRes = response.getEntity(String.class);
response.close();
return authRes;
} else {
return null;
}
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public String getSummary(){
try {
String basePath = "https://xyzhost/summary";
if (client == null) {
client = ClientHelper.createClient();
}
WebResource webResource = client
.resource(basePath);
ClientResponse response = webResource.type("application/x-www-form-urlencoded").accept("application/json")
.post(ClientResponse.class, processFormParams(formParams));
if (response != null) {
String serviceRes = response.getEntity(String.class);
response.close();
return serviceRes;
} else {
return null;
}
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public static void main(String[] args) throws ApiException {
String username = "testuser";
String passwd = "testpasswd";
AuthApi apiTest = new ApiTest();
String auth =apiTest.getAuth(username, passwd);
String reslut1 = apiTest.getSummary();
String result2 = apiTest.getSummary();
String result3 = apiTest.getSummary();
String result4 = apiTest.getSummary();
}
}
So, I use the same client to hit the service under the same host.
I can success get the response for "auth" and "result1" but the client stuck in "result2" in the following part
ClientResponse response = webResource.type("application/x-www-form-urlencoded").accept("application/json")
.post(ClientResponse.class, processFormParams(formParams));
I try to modify the following part:
PoolingHttpClientConnectionManager phcc= new PoolingHttpClientConnectionManager(registry);
phcc.setDefaultMaxPerRoute(10);
then, ApiTest works, won't stuck. I guess there is some issue about the connection, since by default, the max per route for poolingHttpClientConnectionManager is 2, so my ApiTest will stuck in the 3rd request. I think the connection has been release since I have consume the response entity ,
if (response != null) {
String serviceRes = response.getEntity(String.class);
response.close();
return serviceRes;
}
but it seems not work at all, the connection seems not released.
anyone can help ? Appreciate!
I get one solution: switch the version of jersey-client from 1.17 to 1.18 , then problem solved!
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.18</version>
<scope>compile</scope>
</dependency>