Java使用CloseableHttpClient调用第三方接口

1. 依赖

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>

2. 接口

@PostMapping("/webGlLogin")
@ApiOperation(value = "登录")
public ResponseVo webGlLogin(@RequestBody WebGlModel webGlModel) {
    return indexService.webGlLogin(webGlModel);
}

3. 逻辑

public ResponseVo webGlLogin(WebGlModel webGlModel) {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    // post请求
    HttpPost httpPost = new HttpPost("https://www.ilab-x.com/open/api/v2/user/validate?username=" + webGlModel.getUsername()
            + "&password=" + webGlModel.getPassword()
            + "&nonce=" + webGlModel.getNonce()
            + "&cnonce=" + webGlModel.getCnonce()
            + "&appid=" + webGlModel.getAppid()
            + "&signature=" + webGlModel.getSignature());
    httpPost.setHeader("Content-Type", "application/json;charset=utf8");

    // 响应模型
    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            return ResponseVo.success(HttpStatus.SUCCESS, "操作成功", EntityUtils.toString(responseEntity));
        }
    } catch (Exception e) {
        return ResponseVo.error(HttpStatus.ERROR, "请求调用失败", e.getMessage());
    } finally {
        try {
            // 释放资源
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return ResponseVo.error(HttpStatus.ERROR, "服务器异常,请联系管理员", null);
}
### Java调用第三方 API 的方法 在Java中,可以使用多种方式来调用第三方API。以下是几种常见的HTTP客户端库及其简单示例。 #### OkHttp 客户端 OkHttp 是一个高效的支持同步和异步请求的 HTTP 客户端[^1]。下面展示了一个简单的 GET 请求例子: ```java import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class OkHttpClientExample { public static void main(String[] args) throws Exception { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://api.example.com/data") .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new RuntimeException("Unexpected code " + response); System.out.println(response.body().string()); } } } ``` 此代码创建了 `OkHttpClient` 实例并构建了一个GET请求发送到指定URL地址上,在接收到响应之后读取返回的内容字符串形式打印出来。 #### HttpURLConnection 库 对于不需要额外依赖的情况,也可以考虑使用标准库中的 `HttpURLConnection` 来发起网络请求[^2]。这里给出一段利用该类完成相同功能的小程序片段: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpUrlConnectionExample { public static void main(String[] args) throws Exception { URL url = new URL("https://api.example.com/data"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder content = new StringBuilder(); while ((inputLine = in.readLine()) != null) { content.append(inputLine); } in.close(); conn.disconnect(); System.out.println(content.toString()); } } ``` 这段代码同样实现了向目标服务器发出获取数据命令的功能;不过它直接操作底层连接对象来进行交互而无需引入外部包文件。 #### Apache HttpClient 库 Apache HttpClient 提供了一种更高级别的抽象用于简化Web资源访问过程[^3]。下面是采用此类库执行相似任务的一个实例化表达式: ```java 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; public class ApacheHttpClientExample { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("https://api.example.com/data"); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { System.out.println(EntityUtils.toString(response.getEntity())); } finally { httpClient.close(); } } } ``` 上述三种方案各有优劣之处,开发者可以根据具体需求选择最适合的一种工具来实现对外部服务接口调用逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值