Make 2-way TLS call to REST API from Java web application - java

My biggest issue is that I do not have the certificate (public and private key pair). The certificate is installed in the weblogic trust store and is the default certificate presented when making a request to the web application I am just not sure how I can make the call without the certificate loaded on the file system.
I tried using Apache HTTP client and Javax Http Client hoping that when I would make the call it would also send the certificate.
private void testCall(String path) {
URI uri = null;
try {
uri = new URIBuilder().setScheme("https").setHost("secure.url.com")
.setPath("/"+path)
.build();
} catch (URISyntaxException e) {
status = "Error Occured Building URL";
}
HttpGet httpget = new HttpGet(uri);
builtUrl = httpget.getURI().toString();
printContent(httpget);
}
private void printContent(HttpGet getRequest){
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(getRequest);
status = response.getStatusLine().toString();
HttpEntity entity = response.getEntity();
contentRes = EntityUtils.toString(entity );
} catch (ClientProtocolException e) {
status = "Error Occured during Client Protocol" + e.toString();
} catch (ParseException e) {
status = "Error Occured during Parse Protocol" + e.toString();
} catch (IOException e) {
status = "Error Occured during Client Protocol" + e.toString();
}
}

Related

Peer not authenticated exception when connecting SAP Cloud Platform to Office 365 API

I'm implementing an SAP Cloud Platform Java application to connect to the Office 365 API (https://outlook.office.com/) using OAuth2 authentication.
When I running it on Apache Tomcat local server I get the response from the server correctly.
When I run the same code on SAP Cloud Platform I get javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated|
In both cases I get the correct OAuth token.
What am I missing here?
The code I'm using is:
private Object getResponseFromAzure(String url, String methodType) {
AuthenticationResult result = null;
try {
result = getAccessTokenFromUserCredentials(); // OAuth2 bearer token
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String accessToken = result.getAccessToken();
System.out.println("Access Token is - " + accessToken);
HttpClient client = new DefaultHttpClient();
HttpRequestBase request = null;
if ("GET".equals(methodType)) {
request = new HttpGet(url);
} else if ("POST".equals(methodType)) {
request = new HttpPost(url);
}
request.addHeader("Authorization", "Bearer " + accessToken);
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Create a Destination in SCP. Upload the root and intermediate certificates in the Destination service. This is part of the UI.
Connect from your java application using the destination instead of a direct connection. Example code is available at https://help.sap.com/viewer/cca91383641e40ffbe03bdc78f00f681/Cloud/en-US/e592cf6cbb57101495d3c28507d20f1b.html

where is the wrong in this syntax of calling http request get

I have this call (from the browser)
http://serverName:8081/cmp-mg-?sub_x?=7
and it returns 200 response
and I want to call do that request from my web service:
this is my web service:
public Response sendMT2(#BeanParam MT mt) throws IOException {
try {
HttpHost host = new HttpHost("serverName", 8081);
HttpClient client = HttpClientBuilder.create().build();
HttpRequest request = new BasicHttpRequest("GET",
"/serverp/sam?" + mt.getURLParameter());
System.out.println("/cmp-mg-xconn-http-webapp/sam?"
+ mt.getURLParameter());
HttpResponse response = client.execute(host, request);
String responseString = new BasicResponseHandler()
.handleResponse(response);
return Response.ok(responseString).build();
} catch (ClientProtocolException e) {
throw e;
// return Response.status(500).build();
} catch (IOException e) {
throw e;
// return Response.status(500).build();
}
}
but I am getting error
org.apache.http.client.HttpResponseException: Not Found
what is the wrong?
I found the error myself.
before sub-r_mob .. i had ? instead of &

GCM send message from one device to other without any third part server

I am trying to send messages from device to device, without the use of any third part server(Well I do use it for some other parts).
I am using HTTP request to send it to gcm server directly from device.
Heres what I have done.
try {
HttpPost httppost;
try {
httppost = new HttpPost(
"https://android.googleapis.com/gcm/send");
} catch (IllegalArgumentException e) {
e.printStackTrace();
return false;
}
httppost.setHeader("Authorization", "key=512218918480");
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
ArrayList<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("registration_id", id));
postParams.add(new BasicNameValuePair("data.mode",
"exampleContentOfYourMessage"));
postParams.add(new BasicNameValuePair("m",
"exampleContentOfYourMessage"));
HttpResponse response;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity entity;
try {
httppost.setEntity(new UrlEncodedFormEntity(postParams, "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return false;
}
try {
response = httpClient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
entity = response.getEntity();
if (entity != null
&& response.getStatusLine().getStatusCode() == 200) {
return true;
} else {
Log.e("Tag", "No Connection");
return false;
}
} catch (Exception e) {
Log.e("grokkingandroid",
"IOException while sending registration id", e);
}
return false;
}
This returns
02-24 00:19:13.772: W/DefaultRequestDirector(9913): Authentication error: Unable to respond to any of these challenges: {}
So it looks like authentication error for https . DO I need to send something more to gcm server?
I also know the flaws for using this method.My id would be in app so less security.I cant send much data and so on.

Not able to cache HttpResponse using cachingHttpClient in android

public class CacheDemo {
public static void main(String[] args) {
CacheConfig cacheConfig = new CacheConfig();
cacheConfig.setMaxCacheEntries(1000);
cacheConfig.setMaxObjectSizeBytes(1024 * 1024);
HttpClient cachingClient = new CachingHttpClient(new DefaultHttpClient(), cacheConfig);
HttpContext localContext = new BasicHttpContext();
sendRequest(cachingClient, localContext);
CacheResponseStatus responseStatus = (CacheResponseStatus) localContext.getAttribute(
CachingHttpClient.CACHE_RESPONSE_STATUS);
checkResponse(responseStatus);
sendRequest(cachingClient, localContext);
responseStatus = (CacheResponseStatus) localContext.getAttribute(
CachingHttpClient.CACHE_RESPONSE_STATUS);
checkResponse(responseStatus);
}
static void sendRequest(HttpClient cachingClient, HttpContext localContext) {
HttpGet httpget = new HttpGet("http://www.mydomain.com/content/");
HttpResponse response = null;
try {
response = cachingClient.execute(httpget, localContext);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpEntity entity = response.getEntity();
try {
EntityUtils.consume(entity);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static void checkResponse(CacheResponseStatus responseStatus) {
switch (responseStatus) {
case CACHE_HIT:
System.out.println("A response was generated from the cache with no requests "
+ "sent upstream");
break;
case CACHE_MODULE_RESPONSE:
System.out.println("The response was generated directly by the caching module");
break;
case CACHE_MISS:
System.out.println("The response came from an upstream server");
break;
case VALIDATED:
System.out.println("The response was generated from the cache after validating "
+ "the entry with the origin server");
break;
}
}
}
It is not worked for me.
Every time it get the data from the server.not from the cache.
I m using jar "httpclient-cache-4.1-beta1".
You haven't showed us what's going on with your HTTP server. Is the service at mydomain.com/content setting the correct Cache-Control headers on the HTTP response? For caching to work, you need to have your HTTP server or web application indicate if the data can be cached and the length that the data can be cached using the appropriate headers.
Also, check the API documented on CachingHttpClient to see what headers it expects from the web server.

HttpClient Intermittent Page Not Found

I use the following code and run the method multiple times, a few times I get a response in GZIP which is what I expect and a few other times I get a response that is completely different(non GZIP page not found). However if I download the same URL multiple times using Mozilla or IE I consistently get the same GZIP response.
Is this an error with the server I am trying to reach to, or do I need to set any parameters to get a consistent response ?
The URL I am trying to download is the following, can you please let me know ?
public static byte[] dowloadURL(URL urlToDownload) {
InputStream iStream = null;
byte[] urlBytes = null;
try {
//HttpClient httpClient = new HttpClient();
org.apache.http.client.
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(urlToDownload.toString());
HttpResponse response = httpClient.execute(httpget);
iStream = response.getEntity().getContent();
urlBytes = IOUtils.toByteArray(iStream);
String responseString = new String(urlBytes);
System.out.println(" >>> The response string for " +urlToDownload.toString()+ " is " +responseString);
} catch (IOException e) {
System.err.printf("Failed while reading bytes from %s: %s",
urlToDownload.toExternalForm(), e.getMessage());
e.printStackTrace();
// Perform any other exception handling that's appropriate.
} finally {
if (iStream != null) {
try {
iStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return urlBytes;
}

Categories

Resources