Send JSON data in an HTTP GET request to a REST API from JAVA code
28,789
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.
Author by
akshitBhatia
Updated on July 09, 2022Comments
-
akshitBhatia almost 2 years
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