I need to Enable a TLS 1.2 connection in IBM Java 1.6[SR16 FP60]. I tried establishing the connection by
public static void TLS() throws NoSuchAlgorithmException, KeyManagementException, IOException{
System.setProperty("https.protocols", "TLSv1.2");
URL url = new URL("https://jsonplaceholder.typicode.com/posts");
String XML = "<Test></test>"
SSLContext ssl = SSLContext.getInstance("TLSv1.2");
// ctx.init(null, null, null);
ssl.init(null, null, null);
SSLContext.setDefault(ssl);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(ssl.getSocketFactory());
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/xml");
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
os.write(XML.getBytes());
os.flush();
os.close();
System.out.println(">>>Connection certificate"+connection.getServerCertificates());
System.out.println(">>>Connection"+connection.getContent());
int responseCode = connection.getResponseCode();
System.out.println("POST Response Code : " + responseCode);
System.out.println("POST Response Message : " + connection.getResponseMessage());
if (responseCode == HttpsURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in .readLine()) != null) {
response.append(inputLine);
} in .close();
System.out.println(response.toString());}
}
While establishing the connection it's throwing an error
Received Fatal alert : handshake_failure
Please advise us the resolve this issue.
I guess you are using WebSphere 6? You have to upgrade to 7.0.0.23, 8.0.0.3 or 8.5.
See https://developer.ibm.com/answers/questions/206952/how-do-i-configure-websphere-application-server-ss.html
Related
How can i use "sendPost Function", Instead of using more than one "sendPost function" for different requests in NodeJs ?
like this Example,I do 2 sendPost function to send 2 requests.
But the code itself is in the two functions with little change, so I want a way to do one "sendPost" function for both requests.
////////sign up
public static void sendPOST1(String POST_PARAMS) throws Exception {
System.out.println("Sending http");
URL obj = new URL(POST_URL_SU);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-Type", "application/json");
con.setConnectTimeout(50000); // 5 seconds
con.setReadTimeout(50000); // 5 seconds
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
byte[] outputBytesArray = POST_PARAMS.getBytes();
os.write(outputBytesArray);
os.flush();
os.close();
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
// Here it read line line
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Res: " + response.toString());
} else {
System.out.println(con.getResponseMessage());
System.out.println("POST request not worked");
}
}
////////Login
public static void sendPOST2(String POST_PARAMS) throws Exception {
System.out.println("Sending http");
URL obj = new URL(POST_URL_LI);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-Type", "application/json");
con.setConnectTimeout(50000); // 5 seconds
con.setReadTimeout(50000); // 5 seconds
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
byte[] outputBytesArray = POST_PARAMS.getBytes();
os.write(outputBytesArray);
os.flush();
os.close();
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Res: " + response.toString());
} else {
System.out.println(con.getResponseMessage());
System.out.println("POST request not worked");
}
}
You can create a single function sendPost() that takes a URL parameter:
public static void sendPost(String url, String POST_PARAMS) throws Exception {
System.out.println("Sending http");
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-Type", "application/json");
con.setConnectTimeout(50000); // 5 seconds
con.setReadTimeout(50000); // 5 seconds
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
byte[] outputBytesArray = POST_PARAMS.getBytes();
os.write(outputBytesArray);
os.flush();
os.close();
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Res: " + response.toString());
} else {
System.out.println(con.getResponseMessage());
System.out.println("POST request not worked");
}
}
In fact, I suggest you break this function into several smaller functions that do simple tasks.
I'm using the code below to create a http request to my amazon AWS api gateway with an object (mp3Base64) as its content. However, it needs to have the authorization token attached. Can anyone explain how this is done and show an example? Any help is gratefully received. Thanks.
public String executePost(String targetURL, Mp3Base64 mp3Base64) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String mp3Base64Json = mapper.writeValueAsString(mp3Base64);
URL obj = new URL(targetURL);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
connection = (HttpURLConnection) obj.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",
Integer.toString(mp3Base64Json.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes("base64=" + mp3Base64Json);
wr.flush();
wr.close();
//Get Response
int responseCode = connection.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + targetURL);
System.out.println("Post parameters : base64 =" + mp3Base64Json);
System.out.println("Response Code : " + responseCode);
InputStream is = connection.getInputStream();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
return response.toString();
}
My soap API is running on localHost. It is working fine when i access it from the browser or soap UI. But it throws 500 error when I access it from my java client
I tried to debug the code, but could not find anything. The server logs as well does not print anything. Only the tomcat access logs show the response code for the request
public class PostSoapRequest {
String soapEndpointUrl = "http://10.142.240.103:8082/notification-adaptor/services/ChangeTrigger";
public void postRequest(ChangeDeviceTrigger_Element changeDeviceTrigger) {
try {
URL obj = new URL(soapEndpointUrl);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
con.setRequestProperty("SOAPAction", "http://dpa.nokia.com/ChangeDeviceTrigger/");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("User-Agent","Apache-HttpClient/4.1.1");
String xml = RequestXml.getXmlRequest();
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(xml);
wr.flush();
wr.close();
String responseStatus = con.getResponseMessage();
System.out.println("responseStatus :" + responseStatus);
System.out.println("getResponseCode :" + con.getResponseCode());
BufferedReader reader = null;
if (con.getResponseCode() == 200) {
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();
System.out.println("response:" + response.toString());
}else {
reader = new BufferedReader(new InputStreamReader(con.getErrorStream()));
}
System.out.println(reader.read());
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("response:" + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
exception:
java.io.IOException: Server returned HTTP response code: 500 for URL: http://10.142.240.103:8082/notification-adaptor/services/ChangeTrigger
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorI mpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1944)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1939)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1938)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1508)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
at com.nokia.dpa.ChangeDeviceTrigger.post.PostSoapRequest.postRequest(PostSoapRequest.java:49)
at com.nokia.dpa.ChangeDeviceTrigger.post.PostSoapRequest.main(PostSoapRequest.java:65)
Caused by: java.io.IOException: Server returned HTTP response code: 500 for URL: http://10.142.240.103:8082/notification-adaptor/services/ChangeTrigger
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1894)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
at java.net.HttpURLConnection.getResponseMessage(HttpURLConnection.java:546)
at com.nokia.dpa.ChangeDeviceTrigger.post.PostSoapRequest.postRequest(PostSoapRequest.java:30)
I found the soap request xml that was posted to the service endpoint was wrong. There was an extra "\" character in the request. The issue is not fixed
I have this method to connect to my webservice (REST API)
public static void getHttpCon() throws Exception{
String tokenUrl = AppPropertiesService.getProperty( URL_TOKEN );
String username = AppPropertiesService.getProperty( USERNAME );
String password = AppPropertiesService.getProperty( PASSWORD );
String POST_PARAMS = "username="+username+"&password="+password+"&lang=fr&grant_type=password&client_id=apiclient";
URL obj = new URL(tokenUrl);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json;odata=verbose");
con.setRequestProperty("Authorization",
"Basic Base64_encoded_clientId:clientSecret");
con.setRequestProperty("Accept",
"application/x-www-form-urlencoded");
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST request not worked");
}
}
I want to know how can i POSTa CSV File .
Should I do it directly in my method above ?
Do I have to create a new method by recovering the connection token from my method above?
My API ULR is POST /api/{id}/csv
I want to add TLS 1.2 to the below code, Tried by creating socket but no luck. Can someone help on it ? Can we add it after creating a client ?
private static int executeSOAPRequest(String req, String targetURL)
throws Exception {
PostMethod post = new PostMethod(targetURL);
post.setRequestBody(req);
post.setRequestHeader("Content-type",
"text/xml; characterset=ISO-8859-1");
post.setRequestHeader("SOAPAction", "\"\"");
// prepare HTTP Client
HttpClient client = new HttpClient();
client.getParams().setParameter("SOAPAction", "\"\"");
// Post the request
int respCode = client.executeMethod(post);
System.out.println(post.getResponseBodyAsString());
// If response is not success
if (respCode != 200)
throw new Exception("Executing SOAP request has failed.");
// Convert the response into NOM XML
int resp = 0;
Document doc = nomDocPool.lendDocument();
try {
resp = doc.parseString(post.getResponseBodyAsString());
nomDocPool.returnDocument(doc);
} catch (XMLException e) {
nomDocPool.returnDocument(doc);
//logger.error("Exception while generating SAML : "
//+ e);
throw e;
}
System.out.println("resp: "+resp);
return resp;
}
HttpClient already handles TLS for you. This is documented:
http://hc.apache.org/httpclient-3.x/sslguide.html
HttpClient provides full support for HTTP over Secure Sockets Layer (SSL) or IETF Transport Layer Security (TLS) protocols by leveraging the Java Secure Socket Extension (JSSE). JSSE has been integrated into the Java 2 platform as of version 1.4 and works with HttpClient out of the box.
All you have to do is make sure your targetURL is using https:// instead of http://, then HttpClient handles the rest for you.
Forget HttpClient. Use javax.net.ssl.HttpsURLConnection.
String myResponse = null;
URL url = new URL(targetURL);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestProperty("Content-Type", "text/xml; characterset=ISO-8859-1");
con.setRequestProperty("SOAPAction", "\"\"");
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setSSLSocketFactory(My_Lovely_CertificateHelper.getSslSocketFactory());
con.connect();
OutputStream os = con.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "ISO-8859-1");
osw.write(req);
osw.flush();
osw.close();
InputStream is = null;
if (con.getResponseCode() < HttpsURLConnection.HTTP_BAD_REQUEST) {
is = con.getInputStream();
} else {
is = con.getErrorStream();
}
InputStreamReader isr = new InputStreamReader(is, "ISO-8859-1");
int read = -1;
char[] buff = new char[1024];
StringBuilder sb = new StringBuilder();
while ((read = isr.read(buff)) != -1) {
sb.append(buff, 0, read);
}
myResponse = sb.toString();
return myResponse;
getSslSocketFactory()
public static SSLSocketFactory getSslSocketFactory() throws Exception {
SSLContext sc = SSLContext.getInstance("TLSv1.2");
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
String trustStorePath = getcertPath(); //"user.dir" + "\ohHappyDays.jks";
String password = "finallyFoundLoveIn2021";
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(new FileInputStream(trustStorePath), password.toCharArray());
kmf.init(ks, password.toCharArray());
sc.init(kmf.getKeyManagers(), (TrustManager[]) null, (SecureRandom) null);
return sc.getSocketFactory();
}