Using HttpClientUtil for HTTP Requests and JSON Parsing in Java
This article demonstrates how to call third‑party APIs in Java projects by importing the HttpClientUtil utility, performing GET and POST requests (with and without parameters), handling JSON responses with a custom JsonUtils class, and includes complete code examples for each step.
In many projects you need to call third‑party interfaces such as a weather forecast API. The article shows the complete workflow for doing this in a Java backend.
Usage Process
1. Preparation : Import the HttpClientUtil class (or use Spring's RestTemplate) which provides methods for GET and POST requests with and without parameters.
package com.njsc.credit.util;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpClientUtil {
/**
* GET request with parameters
*/
public static String doGet(String url, Map<String, String> param) {
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
HttpGet httpGet = new HttpGet(uri);
response = httpclient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
// ... other doGet/doPost overloads omitted for brevity ...
}2. Create URL and access key : Build the request URL by appending the API key and required parameters (e.g., ID card and real name for an identity‑verification service).
/**
* Identity verification via Juhe API
*/
public boolean identityCheck(String idCard, String realName) {
String key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
String url = "http://op.juhe.cn/idcard/query?key=" + key + "&idcard=" + idCard + "&realname=" + realName;
String result = HttpClientUtil.doGet(url);
// parse result with JsonUtils ...
// return true if verification succeeds
return match;
}3. Request the third‑party API : Use HttpClientUtil.doGet (or doPost) to send the request and obtain a JSON string response.
4. Parse the returned JSON : The article provides a JsonUtils utility class that wraps FastJSON (or Gson) to convert JSON strings to Java objects, extract specific fields, format JSON, and handle malformed JSON.
public final class JsonUtils {
public static final int TYPE_FASTJSON = 0;
public static final int TYPE_GSON = 1;
public static String toJson(final Object obj) {
return JSON.toJSONString(obj);
}
public static <T> T parse(final String json, final Class<T> clazz) {
return JSON.parseObject(json, clazz);
}
public static <E> E parse(final String json, final String path) {
String[] keys = path.split(",");
JSONObject obj = JSON.parseObject(json);
for (int i = 0; i < keys.length - 1; i++) {
obj = obj.getJSONObject(keys[i]);
}
return (E) obj.get(keys[keys.length - 1]);
}
// ... other helper methods omitted for brevity ...
}5. Handle JSON format issues : The correctJson method cleans common malformed patterns (e.g., escaped quotes) before parsing.
Overall, the guide walks through preparing the utility classes, constructing request URLs, sending HTTP GET/POST calls, and converting the JSON responses into usable Java objects, providing ready‑to‑copy code snippets for developers.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
