I'm trying to consume a REST service using a Java client and I obtain java.net.ConnectException: Connection timed out exception.
If I'm using a web client (chrome, firefox) I'm able to retrieve the right answer.
I added in windows firewall an exception for java but this not solve my problem.
My connection is secured.
SSLContext sslContext = SSLContext.getInstance("TLS");
X509TrustManager[] xtmArray = new X509TrustManager[] { new OwnTrustManager() };
sslContext.init(null, xtmArray, new java.security.SecureRandom());
if (sslContext != null) {
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext
.getSocketFactory());
}
HttpsURLConnection
.setDefaultHostnameVerifier(new ISAHostnameVerifier());
public class OwnTrustManager implements X509TrustManager{
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
public class ISAHostnameVerifier implements HostnameVerifier{
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
Business logic is:
URL url = null;
try {
url = new URL("https://16.9.1.82/xxxx/v23/rest");
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
con.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
con.setRequestProperty("Cookie", "----");
con.setRequestProperty("Host", "16.9.1.82");
con.setRequestProperty("Authorization", "Basic U1BQQ19STTFASUJNLkNPTTptYXhhZG1pbg==");
con.connect();
Related
HttpClient =new DefaultHttpClient();
HttpPost post = new HttpPost("https://myulr/token");
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();
parametersBody.add(new BasicNameValuePair("client_id","my-client-id"));
parametersBody.add(new BasicNameValuePair("client_secret","my-secret-key"));
parametersBody.add(new BasicNameValuePair("scope","my-scope"));
parametersBody.add(new BasicNameValuePair("grant_type","client_credentials"));
try{
post.setEntity(new UrlEncodedFormEntity(parametersBody));
HttpResponse httpResponse = httpClient.execute(post);
int code = httpResponse.getStatusLine().getStatusCode();
System.out.println("Code::::: "+code);
String result=EntityUtils.toString(httpResponse.getEntity());
System.out.println("Result: "+result);
}catch(Exception e){
e.printStackTrace();
}
This code is properly executing in JDK8 but if I try to execute it in JDK7, it is throwing javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated exception. I tried to google the issue. I found that we can write X509TrustManager and X509HostnameVerifier. I tried with these implementations also, but still didn't work. Please suggest me how can I execute it in JDK7.
Again if I execute the code with X509TrustManager and X509HostnameVerifier, I am getting "java.net.SocketException: Connection reset"
I just recently researched this and i want to add this - Support for TLS 1.2 first appeared in JDK 7. For compatibility reasons, it is enabled by default on server sockets but disabled on clients.
To change it, I wrote following code and it worked for me:
HttpClient base = new DefaultHttpClient();
SSLContext ctx = SSLContext.getInstance("TLSv1.2");
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;
}
};
X509HostnameVerifier verifier = new X509HostnameVerifier() {
#Override
public void verify(String string, X509Certificate xc) throws SSLException {
}
#Override
public void verify(String string, String[] strings, String[] strings1) throws SSLException {
}
#Override
public boolean verify(String string, SSLSession ssls) {
return true;
}
#Override
public void verify(String arg0, SSLSocket arg1) throws IOException {
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new
SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ssf.setHostnameVerifier(verifier);
ClientConnectionManager ccm = base.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", ssf, 443));
httpClient = new DefaultHttpClient(ccm, base.getParams());
I have a java application that is making an HTTP DELETE to an external REST service. This error gets back to me from the server (running C#):
"Value cannot be null.\r\nParameter name: source\n at System.Linq.Enumerable.Count[TSource](IEnumerable`1 source)\r\n at AppCloud_Framework.Controllers.NotificationItemsController.DeleteNotificationItem(NotificationItem[] notificationItems) in C:\\Users\\jonas\\OneDrive\\VS Projects\\AppCloud Framework\\AppCloud Framework\\Controllers\\NotificationItemsController.cs:line 101\nValue:null"
The thing is, when I setup Postman to make the HTTP request to the same URL, with the same Payload and same HTTP method, the action is successful.
I do not have access to the server to investigate further so I need to find the resolution from the client side. Anyway it appears to be a client side issue.
I've been trying to find the problem myself but haven't succeeded. All I could come up with was to add "application/json" to Accept and Content-Type header properties.
My HTTP client:
public static Response execute(String url, Method method, String body) {
Response response = new Response();
try {
////////////////////////////////////////
// Create a trust manager that does not validate certificate chains
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) {
}
} };
// Install the all-trusting trust manager
final SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
////////////////////////////////////////
URL urlObj = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) urlObj.openConnection();
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod(method.toString());
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
//conn.setRequestProperty("Authorization", _authToken);
if (method == Method.POST || method == Method.PUT || method == Method.DELETE) {
conn.setDoOutput(true);
final OutputStream os = conn.getOutputStream();
os.write(body.getBytes());
os.flush();
os.close();
}
int status = conn.getResponseCode();
//log.info("HTTP request status code: "+status);
InputStream is;
if (status>399){
is = conn.getErrorStream();
}else{
is = conn.getInputStream();
}
if (is==null) return null;
BufferedReader rd = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
String line;
while ((line = rd.readLine()) != null) {
response.body += line;
}
rd.close();
response.statusCode = conn.getResponseCode();
conn.disconnect();
} catch (Exception e) {
//log.error(e.getMessage());
e.printStackTrace();
System.out.println("");
response.exception = e.getMessage();
}
return response;
}
I am making a request with this body(disregard the encoding issue, source of that is somewhere else):
[{"hash":"150a17e99f67ce29fcc600c92eee831d","instanceid":"cb440a6f-44ef-4f05-ab41-143153655b6e","text":"{\"C_FirstAndLastName\":\"und\",\"ContactID\":\"1374231\",\"C_Fax\":\"\"}","queueDate":"2016-10-04T03:18:37"},{"hash":"1a94d9b5acff1a27dfe45be4ca5d9138","instanceid":"fdsfdsf-44ef-4f05-ab41-143153655b6e","text":"{\"C_FirstAndLastName\":\"J?â??rgen\",\"ContactID\":\"323093\",\"C_Fax\":\"fsdfsd-B401-4AD3-AEA1-fdsfsdfsd\"}","queueDate":"2016-10-04T03:18:37"},{"hash":"8e592fb16d464bfd0f90f69818944198","instanceid":"fdsfsdf-44ef-4f05-ab41-143153655b6e","text":"{\"C_FirstAndLastName\":\"Claus\",\"ContactID\":\"2495844\",\"C_Fax\":\"fdsfsdgsd-304D-4E91-8586-fsdfsdfsd\"}","queueDate":"2016-10-04T03:18:37"},{"hash":"d6d226255e62690e50abbfa15c4b5462","instanceid":"cb440a6f-44ef-4f05-ab41-143153655b6e","text":"{\"C_FirstAndLastName\":\"Test J??rgen\",\"ContactID\":\"323093\",\"C_Fax\":\"fdsfsdfsd-B401-4AD3-AEA1-fdsfsdfsdf\"}","queueDate":"2016-10-04T03:18:49"}]
All I had to do was to define encoding in the output stream. Not sure if anyone could help me with that as I have just tried many things and some of it worked, but unfortunately nothing was pointing me into this direction.
os.write(body.getBytes("UTF-8"));
Thanks for your time!
Setup:
I've written a JAVA REST client which authenticates (with username/password) and returns a JSON.
Problem:
This is the exception that I'm getting:
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 401 for URL: https://1.1.1.1/api/count
Code:
public class AnotherDemo {
static {
//for localhost testing only
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
new javax.net.ssl.HostnameVerifier(){
public boolean verify(String hostname,
javax.net.ssl.SSLSession sslSession) {
if (hostname.equals("localhost")) {
return true;
}
return false;
}
});
}
public static void main(String[] args) throws Exception{
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 = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
String urlString = "https://1.1.1.1/api/count";
String username = "admin";
String password = "admin";
String usercredentials = username+":admin"+password;
String basicAuth = "Basic"+ new String (new Base64().encode(usercredentials.getBytes()));
// pass encoded user name and password as header
URL url = new URL(urlString);
// URLConnection conn = url.openConnection();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + basicAuth);
conn.setRequestProperty("Accept", "application/json");
BufferedReader r = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = r.readLine();
while (line != null) {
System.out.println(line);
line = r.readLine();
}
}
}
Can someone tell me what I'm doing wrong?
If I use POSTMAN, everything works fine! I get the JSON!
Thanks,
R
Managed to resolve this question. These are the issues:
This line needs to be corrected and also
String usercredentials = username+":admin"+password;
String basicAuth = "Basic"+ new String (new Base64().encode(usercredentials.getBytes()));
to
String usercredentials = username+":"+password;
String basicAuth = "Basic"+ new String (new Base64().encode(usercredentials.getBytes()));
Also, for the issues with SSL handler or this exception,
com.sun.jersey.api.client.ClientHandlerException: 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
Please add the following LOC:
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 = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
/*
* end of the fix
*/
When I invoke my Webservice I am getting error like below, please explain it how I can solve this problem.
Error is:
fault Description : nulldetail : faultCode:Server.Processing
faultString:'javax.net.ssl.SSLHandshakeException : General SSLEngine
problem' faultDetail:'null'
I am using tomcat server in my local.
I'm using 1.6 Java Runtime Environment and I added Webservice SSL into:
jdk1.6>jre>lib>security>cacerts .
but nothing changed. Do I need configure my tomcat server
I solved the problem . You dont need to any configuration your server . Or JRE .
Just put it this code
public String retrieveMngTracking(ArrayList paramList) throws Exception {
//ı added for SSL
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: " + urlHostName
+ " vs. " + session.getPeerHost());
return true;
}
};
ParamMap paramMap = FlexUtil.getParamMap(paramList);
URL url = new URL(paramMap.getString("url"));
//Call this function for SSL
trustAllHttpsCertificates();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setReadTimeout(20000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-type",
"application/x-www-form-urlencoded");
OutputStream os = conn.getOutputStream();
OutputStreamWriter wr = new OutputStreamWriter(os);
wr.write("pMusteriNo=" + paramMap.getString("pMusteriNo"));
wr.write("&pSifre=" + paramMap.getString("pSifre"));
wr.write("&pSiparisNo=" + paramMap.getString("pSiparisNo"));
wr.write("&pKriter=" + paramMap.getString("pKriter"));
wr.flush();
wr.close();
os.close();
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String response = "";
for (;;) {
String line = br.readLine();
if (line == null)
break;
response += line + "\n";
}
br.close();
conn.disconnect();
return response;
}
public static class miTM implements javax.net.ssl.TrustManager,
javax.net.ssl.X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
}
private static void trustAllHttpsCertificates() throws Exception {
// Create a trust manager that does not validate certificate chains:
javax.net.ssl.TrustManager[] trustAllCerts =
new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new miTM();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc =
javax.net.ssl.SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(
sc.getSocketFactory());
}
Ok everything perfect in my local my local server is tomcat . But When ı want to deploy Weblogic server same error giving . Please explain it why everything work my local but now weblogic server problem.
I am a complete beginner at this and I have been trying to make a connection with the server for quite some time
public class Test {
public static void main(String[] args) throws ClientProtocolException, IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getCredentialsProvider().setCredentials(
new AuthScope("9.5.127.34", 80),
new UsernamePasswordCredentials("root", "passw0rd"));
String url_copied_from_firebug = "https://9.5.127.34/powervc/openstack/volume/v1/115e4ad38aef463e8f99991baad1f809//volumes/3627400b-cd98-46c7-a7e2-ebce587a0b05/restricted_metadata"
HttpGet httpget = new HttpGet(url_copied_from_firebug);
HttpResponse response = httpClient.execute(httpget);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
}
}
The error which I get when I try to run the code is
Exception in thread "main" javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
I have tried changing the port number from 80 to 443 but it is not working. I think I am starting with it and might be missing a lot of things. Please point me in the right direction.
Thanx in advance.
Your problem is not HTTP authentication. Your http client could not verify the ssl certificate for the server with a certificate authority - this is probably because you are using a self-signed certificate.
Look at the HttpClient documentation for instructions about how to customize your client to allow a self-signed certificate.
Here is an example of creating an HttpClient that accepts all certificates and host names - just remember to use it with servers you trust:
private DefaultHttpClient getSSLHttpClient(final URL url) throws RestClientException {
try {
final X509TrustManager trustManager = createTrustManager();
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{trustManager}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, createHostnameVerifier());
AbstractHttpClient base = new DefaultHttpClient();
ClientConnectionManager ccm = base.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme(HTTPS, url.getPort(), ssf));
return new DefaultHttpClient(ccm, base.getParams());
} catch (final Exception e) {
throw new RestClientException(FAILED_CREATING_CLIENT, "Failed creating http client",
ExceptionUtils.getFullStackTrace(e));
}
}
private X509TrustManager createTrustManager() {
X509TrustManager tm = new X509TrustManager() {
#Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
#Override
public void checkServerTrusted(final X509Certificate[] chain, final String authType)
throws CertificateException {
}
#Override
public void checkClientTrusted(final X509Certificate[] chain, final String authType)
throws CertificateException {
}
};
return tm;
}
private X509HostnameVerifier createHostnameVerifier() {
X509HostnameVerifier verifier = new X509HostnameVerifier() {
#Override
public boolean verify(final String arg0, final SSLSession arg1) {
return true;
}
#Override
public void verify(final String host, final String[] cns, final String[] subjectAlts)
throws SSLException {
}
#Override
public void verify(final String host, final X509Certificate cert)
throws SSLException {
}
#Override
public void verify(final String host, final SSLSocket ssl)
throws IOException {
}
};
return verifier;
}
First of all you must configure server.xml file.You must uncomment which line start Connector port="8443"