Various Ways to Call Third‑Party HTTP APIs in Java
This article explains multiple approaches for invoking third‑party HTTP APIs in Java, covering JDK HttpURLConnection, Apache HttpClient, CloseableHttpClient, SpringBoot RestTemplate, and OkHttp, with detailed code examples, configuration steps, and usage patterns for GET and POST requests.
The article provides a comprehensive guide on how to call external HTTP services from Java applications, presenting several common libraries and frameworks along with complete code samples and configuration instructions.
1. JDK HttpURLConnection
Using the native java.net.HttpURLConnection class, the article shows how to implement both GET and POST requests in a single utility method, handling connection setup, timeouts, request properties, response reading, and resource cleanup.
package com.riemann.springbootdemo.util.common.httpConnectionUtil;
import org.springframework.lang.Nullable;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* @author riemann
*/
public class HttpURLConnectionUtil {
/**
* Http get request
* @param httpUrl connection URL
* @return response data
*/
public static String doGet(String httpUrl) {
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
StringBuffer result = new StringBuffer();
try {
URL url = new URL(httpUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(15000);
connection.connect();
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
if (null != is) {
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String temp = null;
while (null != (temp = br.readLine())) {
result.append(temp);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try { br.close(); } catch (IOException e) { e.printStackTrace(); }
}
if (is != null) {
try { is.close(); } catch (IOException e) { e.printStackTrace(); }
}
connection.disconnect();
}
return result.toString();
}
/**
* Http post request
* @param httpUrl connection URL
* @param param parameters
* @return response data
*/
public static String doPost(String httpUrl, @Nullable String param) {
StringBuffer result = new StringBuffer();
HttpURLConnection connection = null;
OutputStream os = null;
InputStream is = null;
BufferedReader br = null;
try {
URL url = new URL(httpUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(15000);
connection.setReadTimeout(15000);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
if (null != param && param.equals("")) {
os = connection.getOutputStream();
os.write(param.getBytes("UTF-8"));
}
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
if (null != is) {
br = new BufferedReader(new InputStreamReader(is, "GBK"));
String temp = null;
while (null != (temp = br.readLine())) {
result.append(temp);
result.append("\r\n");
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } }
if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } }
if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } }
connection.disconnect();
}
return result.toString();
}
public static void main(String[] args) {
String message = doPost("https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "");
System.out.println(message);
}
}2. Apache HttpClient (commons‑httpclient)
Using the older commons‑httpclient library, the article shows how to perform GET requests with HttpClient and GetMethod , handling connection parameters, timeouts, retries, and response processing.
<!--HttpClient-->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.32</version>
</dependency> package com.riemann.springbootdemo.util.common.httpConnectionUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import java.io.IOException;
/**
* @author riemann
*/
public class HttpClientUtil {
public static String doGet(String url, String charset) {
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
GetMethod getMethod = new GetMethod(url);
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
String response = "";
try {
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("请求出错:" + getMethod.getStatusLine());
}
Header[] headers = getMethod.getResponseHeaders();
for (Header h : headers) {
System.out.println(h.getName() + "---------------" + h.getValue());
}
byte[] responseBody = getMethod.getResponseBody();
response = new String(responseBody, charset);
System.out.println("-----------response:" + response);
} catch (HttpException e) {
System.out.println("请检查输入的URL!");
e.printStackTrace();
} catch (IOException e) {
System.out.println("发生网络异常!");
} finally {
getMethod.releaseConnection();
}
return response;
}
public static String doPost(String url, JSONObject json) {
String res = "";
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url);
postMethod.addRequestHeader("accept", "*/*");
postMethod.addRequestHeader("connection", "Keep-Alive");
postMethod.addRequestHeader("Content-Type", "application/json;charset=GBK");
postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
postMethod.addParameter("commentId", json.getString("commentId"));
try {
int code = httpClient.executeMethod(postMethod);
if (code == 200) {
res = postMethod.getResponseBodyAsString();
System.out.println(res);
}
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
public static void main(String[] args) {
System.out.println(doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "GBK"));
System.out.println("-----------分割线------------");
JSONObject jsonObject = new JSONObject();
jsonObject.put("commentId", "13026194071");
System.out.println(doPost("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", jsonObject));
}
}3. Apache CloseableHttpClient (httpclient 4.x)
The newer CloseableHttpClient from the httpclient 4.x series is demonstrated, including token handling, GET/POST methods, JSON payloads via StringEntity , and proper resource closing.
<!--CloseableHttpClient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.32</version>
</dependency> package com.riemann.springbootdemo.util.common.httpConnectionUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
/**
* @author riemann
*/
public class CloseableHttpClientUtil {
private static String tokenString = "";
private static String AUTH_TOKEN_EXPIRED = "AUTH_TOKEN_EXPIRED";
private static CloseableHttpClient httpClient = null;
public static String doGet(String url, String token) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(url);
if (null != tokenString && !tokenString.equals("")) {
tokenString = getToken();
}
httpGet.addHeader("api_gateway_auth_token", tokenString);
httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
try {
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String res = EntityUtils.toString(response.getEntity());
return res;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String doPost(String url, JSONObject json) {
if (null == httpClient) {
httpClient = HttpClientBuilder.create().build();
}
HttpPost httpPost = new HttpPost(url);
if (null != tokenString && tokenString.equals("")) {
tokenString = getToken();
}
httpPost.addHeader("api_gateway_auth_token", tokenString);
httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
try {
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding("UTF-8");
se.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(se);
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String res = EntityUtils.toString(response.getEntity());
return res;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (httpClient != null) {
try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); }
}
}
return null;
}
public static String getToken() {
String token = "";
JSONObject object = new JSONObject();
object.put("appid", "appid");
object.put("secretkey", "secretkey");
if (httpClient == null) {
httpClient = HttpClientBuilder.create().build();
}
HttpPost httpPost = new HttpPost("http://localhost/login");
httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
try {
StringEntity se = new StringEntity(object.toString());
se.setContentEncoding("UTF-8");
se.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(se);
HttpResponse response = httpClient.execute(httpPost);
JSONObject result = (JSONObject) JSONObject.parseObject(String.valueOf(response));
if (result.containsKey("token")) {
token = result.getString("token");
}
} catch (IOException e) {
e.printStackTrace();
}
return token;
}
public static void test(String telephone) {
JSONObject object = new JSONObject();
object.put("telephone", telephone);
tokenString = getToken();
String response = doPost("http://localhost/searchUrl", object);
System.out.println(response);
}
public static void main(String[] args) {
test("12345678910");
}
}4. SpringBoot RestTemplate
SpringBoot’s RestTemplate simplifies HTTP calls; the article shows Maven dependencies, a configuration class to create a RestTemplate bean, and a service class demonstrating GET (via getForEntity and getForObject ) and POST (via postForEntity , postForObject , and exchange ) operations with custom headers and JSON bodies.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
</parent>
<dependencies>
<!--CloseableHttpClient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<!--spring restTemplate-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(15000);
factory.setReadTimeout(5000);
return factory;
}
} import com.alibaba.fastjson.JSONObject;
import com.swordfall.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class RestTemplateToInterface {
@Autowired
private RestTemplate restTemplate;
public User doGetWith1(String url) {
ResponseEntity
responseEntity = restTemplate.getForEntity(url, User.class);
return responseEntity.getBody();
}
public User doGetWith2(String url) {
return restTemplate.getForObject(url, User.class);
}
public String doPostWith1(String url) {
User user = new User("小白", 20);
ResponseEntity
responseEntity = restTemplate.postForEntity(url, user, String.class);
return responseEntity.getBody();
}
public String doPostWith2(String url) {
User user = new User("小白", 20);
return restTemplate.postForObject(url, user, String.class);
}
public String doExchange(String url, Integer age, String name) {
HttpHeaders headers = new HttpHeaders();
headers.add("authorization", "asdfaf2322");
headers.setContentType(MediaType.APPLICATION_JSON);
JSONObject obj = new JSONObject();
obj.put("age", age);
obj.put("name", name);
HttpEntity
request = new HttpEntity<>(obj, headers);
ResponseEntity
responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
return responseEntity.getBody();
}
}5. OkHttp
OkHttp is presented as a modern, efficient HTTP client. The article includes Maven dependency and a utility class offering singleton client creation, synchronous GET and POST methods, header handling, timeout configuration, and error handling.
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.10.0</version>
</dependency> import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Slf4j
public class OkHttpClient {
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static volatile okhttp3.OkHttpClient client;
private static final int MAX_IDLE_CONNECTION = Integer.parseInt(ConfigManager.get("httpclient.max_idle_connection"));
private static final long KEEP_ALIVE_DURATION = Long.parseLong(ConfigManager.get("httpclient.keep_alive_duration"));
private static final long CONNECT_TIMEOUT = Long.parseLong(ConfigManager.get("httpclient.connectTimeout"));
private static final long READ_TIMEOUT = Long.parseLong(ConfigManager.get("httpclient.readTimeout"));
private static okhttp3.OkHttpClient getInstance() {
if (client == null) {
synchronized (okhttp3.OkHttpClient.class) {
if (client == null) {
client = new okhttp3.OkHttpClient.Builder()
.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
.connectionPool(new ConnectionPool(MAX_IDLE_CONNECTION, KEEP_ALIVE_DURATION, TimeUnit.MINUTES))
.build();
}
}
}
return client;
}
public static String syncPost(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder().url(url).post(body).build();
try {
Response response = OkHttpClient.getInstance().newCall(request).execute();
if (response.isSuccessful()) {
String result = response.body().string();
log.info("syncPost response = {}, responseBody= {}", response, result);
return result;
}
String result = response.body().string();
log.info("syncPost response = {}, responseBody= {}", response, result);
throw new IOException("Third‑party interface returned HTTP status " + response.code());
} catch (Exception e) {
log.error("syncPost() url:{} have a exception {}", url, e);
throw new RuntimeException("syncPost() have a exception " + e.getMessage());
}
}
public static String syncGet(String url, Map
headParamsMap) throws IOException {
Request.Builder builder = new Request.Builder().url(url);
if (headParamsMap != null && !headParamsMap.isEmpty()) {
for (Map.Entry
entry : headParamsMap.entrySet()) {
builder.addHeader(entry.getKey(), (String) entry.getValue());
}
}
Request request = builder.build();
try {
Response response = OkHttpClient.getInstance().newCall(request).execute();
String result = response.body().string();
log.info("syncGet response = {},responseBody= {}", response, result);
if (!response.isSuccessful()) {
throw new IOException("Third‑party interface returned HTTP status " + response.code());
}
return result;
} catch (Exception e) {
log.error("remote interface url:{} have a exception {}", url, e);
throw new RuntimeException("Third‑party interface returned exception");
}
}
}Overall, the article equips Java developers with practical code snippets and best‑practice guidelines for interacting with external HTTP services using a range of libraries suited to different project needs.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
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.