5

I am making the following curl request successfully to my API:

curl -v -X GET -H "Content-Type: application/json" -d {'"query":"some text","mode":"0"'} http://host.domain.abc.com:23423/api/start-trial-api/

I would like to know how can i make this request from inside JAVA code. I have tried searching through Google and stack overflow for the solution. All i have found is how to send data through a query string or how to send JSON data through a POST request.

Thanks

akshitBhatia
  • 991
  • 5
  • 10
  • 18
  • What webpages have you seen so far? The difference between GET and POST is very small. – tar May 14 '14 at 04:56
  • You are doing a GET and sending json data in the body. Is that intentional? – Alexandre Santos May 14 '14 at 05:07
  • Please correct me if I'm wrong, but can you even send a body in a GET request? Wouldn't the -d be ignored for a GET? – metacubed May 14 '14 at 05:09
  • @AlexandreSantos Sending body with the GET request is intentional. – akshitBhatia May 14 '14 at 05:51
  • @metacubed The curl request works. I am able to use the data inside the API. I just need to know how to make the same curl request through JAVA code. – akshitBhatia May 14 '14 at 05:52
  • @akshitBhatia Take a look at this highly rated question [HTTP GET with request body](http://stackoverflow.com/questions/978061/http-get-with-request-body). It may work today, but it is definitely **not** recommended. – metacubed May 14 '14 at 05:56
  • You could just open a socket and write the request over the pipe. Read the response back on the same pipe. Of course, people will want to offer the gazillion silly bloated frameworks for that but still, that would be the simplest thing and give you exact control of what you want to pass.. – kg_sYy May 25 '15 at 17:04

4 Answers4

3

Using below code you should be able to invoke any rest API.

Make a class called RestClient.java which will have method for get and post

package test;

import java.io.IOException;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.javamad.utils.JsonUtils;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class RestClient {

    public static <T> T post(String url,T data,T t){
        try {
        Client client = Client.create();
        WebResource webResource = client.resource(url);
        ClientResponse response = webResource.type("application/json").post(ClientResponse.class, JsonUtils.javaToJson(data));

        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                 + response.getStatus());
        }
        String output = response.getEntity(String.class);
        System.out.println("Response===post="+output);

            t=(T)JsonUtils.jsonToJavaObject(output, t.getClass());
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return t;
    }
    public static <T> T get(String url,T t)
    {
         try {
        Client client = Client.create();

        WebResource webResource = client.resource(url);

        ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);

        if (response.getStatus() != 200) {
           throw new RuntimeException("Failed : HTTP error code : "
            + response.getStatus());
        }

        String output = response.getEntity(String.class);
        System.out.println("Response===get="+output);



            t=(T)JsonUtils.jsonToJavaObject(output, t.getClass());
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return t;
    }

}

invoke the get and post method

public class QuestionAnswerService {
    static String baseUrl="http://javamad.com/javamad-webservices-1.0";

    //final String baseUrl="http://javamad.com/javamad-webservices-1.0";
    @Test
    public void getQuestions(){
        System.out.println("javamad.baseurl="+baseUrl);
        GetQuestionResponse gqResponse=new GetQuestionResponse();

        gqResponse =RestClient.get(baseUrl+"/v1/questionAnswerService/getQuestions?questionType=2",gqResponse);


        List qList=new ArrayList<QuestionDetails>();
        qList=(List) gqResponse.getQuestionList();

        //System.out.println(gqResponse);

    }

    public void postQuestions(){
        PostQuestionResponse pqResponse=new PostQuestionResponse();
        PostQuestionRequest pqRequest=new PostQuestionRequest();
        pqRequest.setQuestion("maybe working");
        pqRequest.setQuestionType("2");
        pqRequest.setUser_id("2");
        //Map m= new HashMap();
        pqResponse =(PostQuestionResponse) RestClient.post(baseUrl+"/v1/questionAnswerService/postQuestion",pqRequest,pqResponse);

    }

    }

Make your own Request and response class.

for json to java and java to json use below class

package com.javamad.utils;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JsonUtils {

    private static Logger logger = Logger.getLogger(JsonUtils.class.getName());


    public static <T> T jsonToJavaObject(String jsonRequest, Class<T> valueType)
            throws JsonParseException, JsonMappingException, IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(org.codehaus.jackson.map.DeserializationConfig.Feature.UNWRAP_ROOT_VALUE,false);     
        T finalJavaRequest = objectMapper.readValue(jsonRequest, valueType);
        return finalJavaRequest;

    }

    public static String javaToJson(Object o) {
        String jsonString = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(org.codehaus.jackson.map.DeserializationConfig.Feature.UNWRAP_ROOT_VALUE,true);  
            jsonString = objectMapper.writeValueAsString(o);

        } catch (JsonGenerationException e) {
            logger.error(e);
        } catch (JsonMappingException e) {
            logger.error(e);
        } catch (IOException e) {
            logger.error(e);
        }
        return jsonString;
    }

}

I wrote the RestClient.java class , to reuse the get and post methods. similarly you can write other methods like put and delete...

Hope it will help you.

Nirmal Dhara
  • 1,983
  • 15
  • 27
0

You could use the Jersey client library, if your project is a Maven one just include in your pom.xml the jersey-client and jersey-json artifacts from the com.sun.jersey group id. To connect to a web service you need a WebResource object:

WebResource resource = ClientHelper.createClient().resource(UriBuilder.fromUri("http://host.domain.abc.com:23423/api/").build());

To make a call sending a payload you can model the payload as a POJO, i.e.

class Payload {
    private String query;
    private int mode;

    ... get and set methods
}

and then call the call using the resource object:

Payload payload = new Payload();

payload.setQuery("some text"); payload.setMode(0);

ResultType result = service  
    .path("start-trial-api").  
    .type(MediaType.APPLICATION_JSON)  
    .accept(MediaType.APPLICATION_JSON)  
    .get(ResultType.class, payload);

where ResultType is the Java mapped return type of the called service, in case it's a JSON object, otherwise you can remove the accept call and just put String.class as the get parameter and assign the return value to a plain string.

remigio
  • 4,046
  • 1
  • 24
  • 27
0

Spring's RESTTemplate is also useful for sending all REST requests i.e. GET , PUT , POST , DELETE

By using Spring REST template, You can pass JSON request with POST like below,

You can pass JSON representation serialized into java Object using JSON serializer such as jackson

RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>();
list.add(new MappingJacksonHttpMessageConverter());
restTemplate.setMessageConverters(list);
Person person = new Person();
String url = "http://localhost:8080/add";
HttpEntity<Person> entity = new HttpEntity<Person>(person);

// Call to Restful web services with person serialized as object using jackson
ResponseEntity<Person> response = restTemplate.postForEntity(  url, entity, Person.class);
Person person = response.getBody();
Pramod S. Nikam
  • 3,597
  • 3
  • 24
  • 51
0

Struggled on the same question and found a nice solution using the gson.

The code:

// this method is based on gson (see below) and is used to parse Strings to json objects
public static JsonParser jsonParser = new JsonParser();

public static void getJsonFromAPI() {
    // the protocol is important
    String urlString = "http://localhost:8082/v1.0/Datastreams"
    StringBuilder result = new StringBuilder();

    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;  // reading the lines into the result
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        rd.close();
        // parse the String to a jsonElement
        JsonElement jsonObject = jsonParser.parse(result.toString());  
        System.out.println(jsonObject.getAsJsonObject()  // object is a mapping
                .get("value").getAsJsonArray()  // value is an array
                .get(3).getAsJsonObject()  // the fourth item is a mapping 
                .get("name").getAsString());  // name is a String

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The packages:

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;

My pom.xml:

<!--    https://mvnrepository.com/artifact/com.google.code.gson/gson -->
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.5</version>
    </dependency>

I hope this helps you!