Java工具类之基于rpc调用第三方接口

该代码示例展示了如何在Java中利用Spring框架的RestTemplate组件执行HTTPGET,POST,PUT,DELETE请求,并进行授权、错误处理。方法包括设置HTTP头、发送请求及获取响应体。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法比较全,关注博主不迷路~

import com.uav.common.exception.base.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class HttpClient {

    @Autowired
    RestTemplate restTemplate;

    static final String AUTHORIZATION = "Authorization";

    static final String ERROR_MSG = " rpc调用异常!";

    public String httpGetByUrl(String  token, String url, Map<String, Object> param){
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.add(AUTHORIZATION, token);
        HttpEntity<Object> httpRequest = new HttpEntity<>(httpHeaders);
        ResponseEntity<String> response = null;
        try {
            response = restTemplate.exchange(url + getParamString(param), HttpMethod.GET, httpRequest, String.class, new HashMap<>());
        } catch (Exception e) {
            log.error("HttpClient.httpGetByUrl.response.error:", e);
            throw new BaseException(url + ERROR_MSG);
        }
        return response.getBody();
    }

    public String httpPostByUrl(String  token, String url, Object requestObj){
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.add(AUTHORIZATION, token);
        HttpEntity<Object> httpRequest = new HttpEntity<>(requestObj, httpHeaders);
        String response = null;
        try {
            response = restTemplate.postForObject(url, httpRequest, String.class);
        } catch (Exception e) {
            log.error("HttpClient.httpPost.response.error:", e);
            throw new BaseException(url + ERROR_MSG);
        }
        return response;
    }


    public String httpPutByUrl(String  token, String url, Object requestObj){
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.add(AUTHORIZATION, token);
        HttpEntity<Object> httpRequest = new HttpEntity<>(httpHeaders);
        String response = null;
        try {
            ResponseEntity<String > res = restTemplate.exchange(url, HttpMethod.PUT, httpRequest, String .class,
                    requestObj);
            response = res.getBody();
        } catch (Exception e) {
            log.error("HttpClient.httpPut.response.error:", e);
            throw new BaseException(url + ERROR_MSG);
        }
        return response;
    }

    public String httpDeleteByUrl(String  token, String url, Object requestObj){
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.add(AUTHORIZATION, token);
        HttpEntity<Object> httpRequest = new HttpEntity<>(httpHeaders);
        String response = null;
        try {
            ResponseEntity<String > res = restTemplate.exchange(url, HttpMethod.DELETE, httpRequest, String .class,
                    requestObj);
            response =  res.getBody();
        } catch (Exception e) {
            log.error("HttpClient.httpDelete.response.error:", e);
            throw new BaseException(url + ERROR_MSG);
        }
        return response;
    }

    // 调用示例  注入本类 然后直接.method
    public static void main(String[] args) {
        String token = "";
        String url = "";
        Map<String, Object> map = new HashMap<>();
        map.put("name","0124");
        map.put("age","1");
        map.put("sex","1");
//        String a = httpClient.httpPostByUrl(token,url,map);

    }
    private String getParamString(Map<String, Object> param) {
        if (param == null) {
            return "";
        }
        StringBuilder paramBuilder = new StringBuilder();
        paramBuilder.append("?");
        for (Map.Entry<String, Object> item : param.entrySet()) {
            paramBuilder.append(item.getKey()).append("=").append(item.getValue())
                    .append("&");
        }
        String result = paramBuilder.toString();
        return result.substring(0, result.length() - 1);
    }

}
### Java调用第三方 API 接口获取数据 在Java应用程序中,可以使用多种方式来调用第三方API接口并处理响应的数据。对于HTTP请求来说,`HttpURLConnection`类是一个内置的选择;然而,在现代开发实践中更推荐采用像Apache HttpClient或是OkHttp这样的库,因为它们提供了更加简洁易用的API以及更好的性能。 下面展示了一个利用HttpClient发送GET请求到指定URL,并读取返回JSON字符串作为响应的例子[^1]: ```java import org.apache.http.HttpResponse; 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 ApiClientExample { public static void main(String[] args) throws Exception { String url = "https://api.example.com/data"; try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpGet request = new HttpGet(url); // 可选:设置请求头信息 request.addHeader("User-Agent", "MyApp/1.0"); CloseableHttpResponse response = null; try { response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { // HTTP OK status code is 200. String responseBody = EntityUtils.toString(response.getEntity()); System.out.println("Response Body:"); System.out.println(responseBody); } else { System.err.printf("Failed to get data, Status Code: %d%n", statusCode); } } finally { if (response != null) { response.close(); } } } } } ``` 这段代码创建了一个简单的客户端程序,它向给定的目标地址发起一个GET请求,并打印出服务器返回的内容。如果需要解析JSON格式的结果,则可以根据实际情况引入Jackson或Gson等序列化工具包来进行进一步的操作。 当涉及到具体业务逻辑时,比如通过USDT RPC API查询余额或其他操作,可以通过调整上述模板中的URL和其他参数来适应特定需求。例如,针对USDT的RPC调用可能看起来如下所示[^2]: ```java // 假设已经配置好了RpcClient实例client LinkedHashMap result = (LinkedHashMap) client.invoke("omni_getinfo", new Object[]{}, Object.class); System.out.println(result.get("balance")); ``` 此片段展示了如何执行一次名为`omni_getinfo`的方法调用来检索账户信息,并从中提取余额字段显示出来。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr.杨先森

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值