How to execute rest api from java and capture the response? - java

Executing this url on my browser: http://localhost:3161/devices/simulator/stop
I don't need login for it. It returns this rest api xml:
<response>
<type>response</type>
<ts>1463749194000</ts>
<status>OK</status>
<msg-version>2.3.0</msg-version>
<op>stop</op>
<data/>
</response>
How can I execute this from JAVA and then capture the xml response?

As other mentioned in this post, it is generic thing, you would be able to find it online already..
I know there are clients to call the REST services from Java. Two of them are listed for your case.
case -1 : if you are using Jersey REST API. Here to capture XML , you can go with your own way,for example use JAXB and XML elements to Java Bean properties.
import java.io.IOException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import org.apache.http.client.ClientProtocolException;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
public class Test {
public static void main(String[] args) throws ClientProtocolException, IOException {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(UriBuilder.fromUri('http://localhost:3161/devices/simulator/stop').build());
// getting XML data
System.out.println(service. path('restPath').path('resourcePath').accept(MediaType.APPLICATION_JSON).get(String.class));
// getting JSON data
System.out.println(service. path('restPath').path('resourcePath').accept(MediaType.APPLICATION_XML).get(String.class));
}
}
Case 2: using HTTP method, it is simple method but parse XML instead of printing it here
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class Test {
public static void main(String[] args) throws ClientProtocolException, IOException {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet('http://localhost:3161/devices/simulator/stop');
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
String line = '';
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
}
}

Related

File Upload Using Rest API Client in JAVA

I have created a client rest api to upload a file on the api endpoints. But this is giving me error:
Exception in thread "main" org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=multipart/form-data, type=class org.glassfish.jersey.media.multipart.FormDataMultiPart, genericType=class org.glassfish.jersey.media.multipart.FormDataMultiPart.
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:191)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:139)
at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1005)
at org.glassfish.jersey.client.ClientRequest.writeEntity(ClientRequest.java:430)
at org.glassfish.jersey.client.HttpUrlConnector._apply(HttpUrlConnector.java:287)
at org.glassfish.jersey.client.HttpUrlConnector.apply(HttpUrlConnector.java:200)
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:215)
at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:635)
at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:632)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:421)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:632)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:392)
at org.glassfish.jersey.client.JerseyInvocation$Builder.post(JerseyInvocation.java:301)
at Test.main(Test.java:35)
Here is my client rest api code:
import java.io.File;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.MultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
public class Test {
public void configureClient(ClientConfig config) {
config.register(MultiPartFeature.class);
}
public static void main(String[] args) {
Client client = ClientBuilder.newClient().register(MultiPart.class);
WebTarget server = client.target("http://localhost:8080/repositories/file/upload");
FileDataBodyPart filePart = new FileDataBodyPart("file", new File("C:\\Users\\kunal\\Downloads\\JWTUtility.java"));
filePart.setContentDisposition(FormDataContentDisposition.name("file").fileName("JWTUtility.java").build());
MultiPart multipartEntity = new FormDataMultiPart().bodyPart(filePart);
Response result = server.request().post(Entity.entity(multipartEntity, multipartEntity.getMediaType()));
System.out.println(result.getStatus());
System.out.println(result.readEntity(String.class));
result.close();
//assertEquals(Response.Status.OK.getStatusCode(), result.getStatus());
}
}
API Endpoint code:
package com.howtodoinjava.jersey;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
#Path("/upload")
public class JerseyService
{
#POST
#Path("/pdf")
#Consumes({MediaType.MULTIPART_FORM_DATA})
public Response uploadPdfFile( #FormDataParam("file") InputStream fileInputStream,
#FormDataParam("file") FormDataContentDisposition fileMetaData) throws Exception
{
String UPLOAD_PATH = "D://Test/";
try
{
int read = 0;
byte[] bytes = new byte[1024];
OutputStream out = new FileOutputStream(new File(UPLOAD_PATH + fileMetaData.getFileName()));
while ((read = fileInputStream.read(bytes)) != -1)
{
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e)
{
throw new WebApplicationException("Error while uploading file. Please try again !!");
}
return Response.ok("Data uploaded successfully !!").build();
}
}
In the client side, you need to add support for the multipart/form-data feature which will register the needed reader and writer:
public class Test {
public void configureClient(ClientConfig config) {
config.register(MultiPartFeature.class);
}
public static void main(String[] args) {
DefaultClientConfig config = new DefaultClientConfig();
configureClient(config);
Client client = ClientBuilder.newClient(config);
WebTarget server = client.target("http://localhost:8080/repositories/file/upload");
// or alternatively at the WebTarget level
// server.register(MultiPartFeature.class);
// ...
}
}

java.lang.NoClassDefFoundError: org/apache/http/ssl/TrustStrategy, though it is present in classpath

I am running an application on tomcat server. I am getting following error while callling a specific function :
java.lang.NoClassDefFoundError: org/apache/http/ssl/TrustStrategy
My class is :
import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.util.Map;
import javax.net.ssl.SSLContext;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
/*import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;*/
//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.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;
import org.performics.air.business.common.data.HttpParam;
public class SendAndReceiveUtil implements Serializable {
//FIXME: move to suitable package
/**
*
*/
private static final long serialVersionUID = 2649891233958197253L;
private static Logger LOG = Logger.getLogger(SendAndReceiveUtil.class);
public static String httpPostWithTLS(String request,String url,Map<String,String> headerParameterMap){
String responseStr = null;
try{
// FIXME: need to handle supplier timeout and gzip
String contentType="";
String soapAction="";
boolean zipForRequest=false;
boolean acceptEncoding = false;
boolean zipForResponse=false;
if (headerParameterMap!=null){
contentType=headerParameterMap.get(HttpParam.CONTENTTYPE.toString())!=null?headerParameterMap.get(HttpParam.CONTENTTYPE.toString()):"";
zipForRequest=(headerParameterMap.containsKey(HttpParam.ZIPFORREQUEST.toString()))? new Boolean(headerParameterMap.get(HttpParam.ZIPFORREQUEST.toString())):false;
acceptEncoding=(headerParameterMap.containsKey(HttpParam.ACCEPT_ENCODING.toString()))? new Boolean(headerParameterMap.get(HttpParam.ACCEPT_ENCODING.toString())):false;
zipForResponse=(headerParameterMap.containsKey(HttpParam.ZIPFORRESPONSE.toString()))? new Boolean(headerParameterMap.get(HttpParam.ZIPFORRESPONSE.toString())):false;
soapAction=headerParameterMap.get(HttpParam.SOAPACTION.toString())!=null?headerParameterMap.get(HttpParam.SOAPACTION.toString()):"";
}
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null,new TrustSelfSignedStrategy()).build();
// Allow TLSv1.2 protocol only, use NoopHostnameVerifier to trust self-singed cert
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,new String[] { "TLSv1.2" }, null, new NoopHostnameVerifier());
//do not set connection manager
HttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("SOAPAction", soapAction);
StringEntity mEntity = new StringEntity(request, "UTF-8");
if(StringUtils.isNotBlank(contentType)){
mEntity.setContentType(contentType);
mEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,contentType));
}else{
mEntity.setContentType("text/xml;charset=UTF-8");
mEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING,"gzip"));
}
httpPost.addHeader("Content-Encoding", "gzip" );
httpPost.addHeader("Accept-Encoding", "gzip,deflate" );
if(null!=headerParameterMap.get("Cookie")){
httpPost.addHeader("Cookie", headerParameterMap.get("Cookie"));
}
httpPost.setEntity(mEntity);
HttpResponse response = httpclient.execute(httpPost);
HttpEntity et=response.getEntity();
ByteArrayOutputStream os = new ByteArrayOutputStream();
et.writeTo(os);
responseStr = new String(os.toByteArray());
}catch(Exception e){
LOG.error(e.getMessage(), e);
}
return responseStr;
}
}
Error comes on calling httpPostWithTLS() function. I searched about it on net and found that class was available at compile but is not available at run time, but i am unable to correct it.
I am using following http jars:
commons-httpclient-3.1.jar
httpclient-4.5.3.jar
httpcore-4.4.6.jar
httpclient-cache-4.5.3.jar
httpclient-win-4.5.3.jar
httpmime-4.5.3.jar
Try to add the httpcore-4.4.6.jar and httpclient-cache-4.5.3.jar to server library and check.
I do face the similar issue after adding these jar file, my problem is resolved.
Thanks,

File name missing in REST API via HTTP Post

I am doing a program which can take the file as input and send http://IPaddress:port_number/etc via REST API HTTP Post method, it will return me my file information in JSON format but in the return of my JSON data, I found out my file name and file type were missing. I only have two program doing the job ,one is sending the file to my server which install in VMware and one is receiving the JSON data from my server, my server only installed a malware scanning engine only Here is my JSON data return from my server
{
   "data_id":"7860ee33d8f14f8f931860dcf97d69a2",
   "file_info":{
      "display_name":"",
      "file_size":289,
      "file_type":"Not available",
      "file_type_description":"Not available",
      "md5":"b294bdea53f3a038d263d8b2e7cafbbc",
      "sha1":"b869fd379cb9743b6c0994494f3ea91a133622cd",
      "sha256":"0f88b399aa65ad75a4e0d1d03acfd31731c68ea54d5f4f5053d6904d192e5e22",
      "upload_timestamp":"2016-11-21T09:48:58.675Z" },
I had tested several code in online but it's also fail to display the file name in the JSON data, display_name will be the file name for my file. May I know is it because some information being miss out in the header and how do I include the file name during the return JSON data ? Here is my java source code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.activation.MimetypesFileTypeMap;
import java.io.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
public class SentFile {
public static void main(String [] args) throws ClientProtocolException, IOException
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.0.25:8008/file");
// File file = new File("testScanFile.txt");
//FileInputStream fileInputStream = new FileInputStream(file);
FileBody bin = new FileBody(new File("testScanFile.txt"));
// String mimeType = new MimetypesFileTypeMap().getContentType("testScanFile.txt");
HttpEntity reqEntity = MultipartEntityBuilder.create()
// .addBinaryBody("bin", new File("testScanFile.txt"),ContentType.APPLICATION_JSON,"testScanFile.txt").build();
.addPart("display_name", bin)
// .addPart("file",bin);
.build();
// post.addHeader("content-type","application/json");
// post.addHeader("Accept","application/json");
post.setEntity(reqEntity);
//InputStream is = new FileInputStream(file);
// post.setEntity(new FileEntity(file));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
// System.out.println(line);
PrintStream ps = new PrintStream(new FileOutputStream("data_id.txt"));
ps.print(line);
ps.close();
}
}
}

ActiveMQ Handling Messages thru REST

I am new to ActiveMQ, we had a ActiveMQ Server else where location, we are unable to connect thru tcp socket, But able to cousume the message using REST command
http://admin:admin#localhost:8161/api/message?destination=queue://orders.input
I have 99K+ messages in ActiveMQ, need consume using REST command and need to store in a text file,
import static com.jayway.restassured.RestAssured.given;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.dnb.e2e.automation.util.CommonUtil;
import com.dnb.e2e.automation.util.WebServiceUtil;
import com.jayway.restassured.RestAssured;
import com.jayway.restassured.config.SSLConfig;
import com.jayway.restassured.config.SessionConfig;
import com.jayway.restassured.response.Headers;
public class MQwithRest {
public static String getResponse() throws Exception
{
String url = "http://admin:admin#localhost:8161/api/message?destination=queue://SAMPLEQUEUE";
String response = "a";
while(response!=""){
try {
response = given().header("content-type", "application/json")
.request()
.config(RestAssured.config().sslConfig(new SSLConfig().allowAllHostnames()))
.when().get(url).asString();
System.out.println(response);
} catch (Exception e) {
e.printStackTrace();
}
}
return "empty";
}
public static void main(String args[]) throws Exception
{
System.out.println(MQwithRest.getResponse());
}
}
In the above code i am displaying consumed messages at output side. When I am implementing thru rest i am able to consume only one message at a time per session.
Can any body help for Consuming 99k+ message with in a single session using REST service?
You can also tunnel JMS client over HTTP.
That way, you can get bypass any non-HTTP restrictions in your network and still use the JMS terminology.
Using the rest web app bundled you are a bit limited to the semantics of retrieving messages. Anyway, you should be able to get all messages using plain HTTP/Rest anyway. Simply use a loop to get messages.

import error for http package in java linux

Hi i use linux and when i try to import the following packages compilation is giving error.
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import com.google.gson.Gson;
How can i install these packages in my linux and then compile. My code as follows,
class pojo1
{
String name=abc;
String age=18;
//generate setter and getters
}
public class SimpleURL
{
public static void main(String[] args)
{
String postUrl="www.site.com";// put in your url
Gson gson= new Gson();
HttpPost post = new HttpPost(postUrl);
StringEntity postingString = new StringEntity(gson.toJson(pojo1));//convert your pojo to json
post.setEntity(postingString);
post.setHeader("Content-type","application/json");
HttpResponse response = httpClient.execute(post);
}
}
Try
javac -cp .;httpclient.jar MyClass.java
java -cp .;httpclient.jar MyClass

Categories