简体   繁体   中英

Send JSON data in an HTTP GET request to a REST API from JAVA code

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

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.

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, ie

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.

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

By usingSpring 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();

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM