can we consume get api along with request body in java 8?
Yes we can call GET API with Request Body and Headers in Java and Spring Boot
- Using Spring Boot Rest Template:
RestTemplate doesn’t support Http Get request with a Request Body because it not implement HttpEntityEnclosingRequestBase by default. But we can make.
a)
import org.apache.http.client.methods.HttpUriRequest;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import java.net.URI;
public final class CustomHttpComponentsClientHttpRequestFactory extends HttpComponentsClientHttpRequestFactory {
@Override
protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
if (HttpMethod.GET.equals(httpMethod)) {
return new HttpGetPost(uri);
}
return super.createHttpUriRequest(httpMethod, uri);
}
}
b)
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.springframework.http.HttpMethod;
import java.net.URI;
public final class HttpGetPost extends HttpEntityEnclosingRequestBase {
public HttpGetPost(final URI uri) {
super.setURI(uri);
}
@Override
public String getMethod() {
return HttpMethod.GET.name();
}
}
c)
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
public class RestTemplateGetWithBody {
static String url = "http://localhost:8088/rest-template/get-with-body";
public static void main(String[] args) {
call();
}
public static void call() {
RestTemplate restTemplate = new RestTemplateBuilder().build();
restTemplate.setRequestFactory(new CustomHttpComponentsClientHttpRequestFactory()); // set our custom Request Factory
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON); // Please set the proper content type here otherwise it will throw error
HttpEntity<Object> entity = new HttpEntity<>("{\"id\":\"1234\"}", headers);
try {
ResponseEntity<Object> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, Object.class);
System.out.println(responseEntity);
} catch (Exception e) {
e.printStackTrace();
}
}
}
- Using Apache HttpClient
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class HttpClientGetBody {
public static void call() throws Exception {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
StringEntity input = new StringEntity("{\"qty\":100,\"name\":\"iPad 4\"}");
//input.setContentType("application/json");
HttpUriRequest request = RequestBuilder.get("http://localhost:8088/rest-template/get-with-body")
.setEntity(input)
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.build();
HttpResponse response = httpClient.execute(request);
//verify the valid error code first
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
throw new RuntimeException("Failed with HTTP error code : " + statusCode);
}
//Now pull back the response object
HttpEntity httpEntity = response.getEntity();
String apiOutput = EntityUtils.toString(httpEntity);
System.out.println(apiOutput);
}
}
}
3 Likes
below is another solution with httpclient
public static String get(String url) throws IOException, ParseException {
String resultContent = null;
HttpGet httpGet = new HttpGet(url);
CloseableHttpClient httpclient = HttpClients.createDefault();
httpGet.addHeader("content-type", "application/json");
Map<String, Object> leadRequest = new HashMap<>();
leadRequest.put("funding_loan_no","1234");
ObjectMapper objectMapper = new ObjectMapper();
String request = objectMapper.writeValueAsString(leadRequest);
httpGet.setEntity(new StringEntity(request));
CloseableHttpResponse response = httpclient.execute(httpGet);
// Get status code
System.out.println(response.getVersion()); // HTTP/1.1
System.out.println(response.getCode()); // 200
System.out.println(response.getReasonPhrase()); // OK
org.apache.hc.core5.http.HttpEntity entity = response.getEntity();
// Get response information
resultContent = EntityUtils.toString(entity);
return resultContent;
}
2 Likes
@hariom.chaudhary But there in no such method (setEntity) in HttpGet class in v4.0
httpGet.setEntity(new StringEntity(request));
@naveen.gupta we need to use http client version 5.x for this
1 Like