Implementing HTTP Client Requests in Java Backend Services
To perform HTTP requests from a Java backend, include the FastJSON library in your project dependencies.
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
Here's a practical implementation using Apache HttpClient to fetch and process JSON data from an extenral API endpoint.
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.*;
@RestController
@RequestMapping("/api")
public class ExternalApiClient {
@GetMapping("/fetchWorkflowTemplates")
public List<Map<String, Object>> retrieveFilteredTemplates(@RequestParam(value = "criteria", required = false) String criteria) {
String endpoint = "http://api.example.com:8080/workflow/templates";
if (criteria != null && !criteria.trim().isEmpty()) {
endpoint += "?filter=" + criteria;
}
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet request = new HttpGet(endpoint);
String responseContent = null;
try (CloseableHttpResponse response = httpClient.execute(request)) {
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
responseContent = EntityUtils.toString(responseEntity);
}
} catch (IOException e) {
e.printStackTrace();
return Collections.emptyList();
}
List<Map<String, Object>> resultList = new ArrayList<>();
if (responseContent != null) {
JSONArray jsonArray = JSONArray.parseArray(responseContent);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
resultList.add(convertJsonToMap(jsonObj));
}
}
return resultList;
}
private Map<String, Object> convertJsonToMap(JSONObject jsonObject) {
Map<String, Object> mapResult = new HashMap<>();
for (String key : jsonObject.keySet()) {
mapResult.put(key, jsonObject.get(key));
}
return mapResult;
}
}
The controller method retrieveFilteredTemplates constructs a URL with an optional filter parameter, executes an HTTP GET request, and converts the JSON response into a list of maps. The convertJsonToMap helper method tarnsforms individual JSON objects into Java Map instances.
For more complex JSON structures with nested objects and arrays, consider this enhanced conversion method:
private Map<String, Object> convertComplexJsonToMap(JSONObject jsonObject) {
Map<String, Object> resultMap = new HashMap<>();
for (String key : jsonObject.keySet()) {
Object value = jsonObject.get(key);
if (value instanceof JSONArray) {
value = convertJsonArrayToList((JSONArray) value);
} else if (value instanceof JSONObject) {
value = convertComplexJsonToMap((JSONObject) value);
}
resultMap.put(key, value);
}
return resultMap;
}
private List<Object> convertJsonArrayToList(JSONArray jsonArray) {
List<Object> listResult = new ArrayList<>();
for (int i = 0; i < jsonArray.size(); i++) {
Object element = jsonArray.get(i);
if (element instanceof JSONArray) {
element = convertJsonArrayToList((JSONArray) element);
} else if (element instanceof JSONObject) {
element = convertComplexJsonToMap((JSONObject) element);
}
listResult.add(element);
}
return listResult;
}