java对接第三方接口的3种常用方式

 更新时间:2024年04月27日 15:39:58   作者:acgchan  
java语言中调用第三方接口,可以使用的方法有很多,下面这篇文章主要给大家介绍了关于java对接第三方接口的3种常用方式,文中通过代码介绍的非常详细,需要的朋友可以参考下

在日常工作中,经常需要跟第三方系统对接,我们做为客户端,调用他们的接口进行业务处理,常用的几种调用方式有:

1.原生的Java.net.HttpURLConnection(jdk);

2.再次封装的HttpClient、CloseableHttpClient(Apache);

3.Spring提供的RestTemplate;

当然还有其他工具类进行封装的接口,比如hutool的HttpUtil工具类,里面除了post、get请求外,还有下载文件的方法downloadFile等。

HttpURLConnection调用方法

HTTP正文的内容是通过OutputStream流写入,向流中写入的数据不会立即发送到网络,而是存在于内存缓冲区中,待流关闭时,根据写入的内容生成HTTP正文。

调用getInputStream()方法时,会返回一个输入流,用于从中读取服务器对于HTTP请求的返回报文

@Slf4j
public class HttpURLConnectionUtil {
   /**
     *
     * Description: 发送http请求发送post和json格式
     * @param url          请求URL
     * @param params    json格式的请求参数
     */
    public static String doPost(String url, String params) throws Exception {

        OutputStreamWriter out = null;
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        URL httpUrl = null; // HTTP URL类 用这个类来创建连接
        try {
            // 创建URL
            httpUrl = new URL(url);
            log.info("--------发起Http Post 请求 ------------- url:" + url + "---------params:" + params);

            // 建立连接
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            //设置请求的方法为"POST",默认是GET
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("connection", "keep-alive");
            conn.setUseCaches(false);// 设置不要缓存
            conn.setInstanceFollowRedirects(true);
            //由于URLConnection在默认的情况下不允许输出,所以在请求输出流之前必须调用setDoOutput(true)
            conn.setDoOutput(true);
            // 设置是否从httpUrlConnection读入
            conn.setDoInput(true);
            //设置超时时间
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.connect();
            // POST请求
            out = new OutputStreamWriter(conn.getOutputStream());
            out.write(params);
            out.flush();
            // 读取响应
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String lines;
            while ((lines = reader.readLine()) != null) {
                response.append(lines);
            }
            reader.close();
            // 断开连接
            conn.disconnect();
        } catch (Exception e) {
            log.error("--------发起Http Post 请求 异常 {}-------------", e);
            throw new Exception(e);
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                log.error(String.valueOf(ex));
            }
        }
        return response.toString();
    }
}

CloseableHttpClient调用

CloseableHttpClient 是一个抽象类,实现了httpClient接口,也实现了java.io.Closeable;

支持连接池管理,可复用已建立的连接 PoolingHttpClientConnectionManager

通过 httpClient.close() 自动管理连接释放

支持HTTPS访问 HttpHost proxy = new HttpHost(“127.0.0.1”, 8080, “http”);

@Slf4j
public class CloseableHttpClientUtil {
    /**
    *url 第三方接口地址
    *json 传入的报文体,可以是dto对象,string、json等
    *header 额外传入的请求头参数
    */    
  public static String doPost(String url, Object json,Map<String,String> header) {

        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost httpPost= new HttpPost(url);//post请求类型
        String result="";//返回结果
        String requestJson="";//发送报文体
        try {
            requestJson=JSONObject.toJSONString(json);
            log.info("发送地址:"+url+"发送报文:"+requestJson);
            //StringEntity s = new StringEntity(requestJson, Charset.forName("UTF-8"));
            StringEntity s= new StringEntity(requestJson, "UTF-8");
               // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
               httpPost.setHeader("Content-Type", "application/json;charset=utf8");
            httpPost.setEntity(s);
            if(header!=null){
                Set<String> strings = header.keySet();
                for(String str:strings){
                    httpPost.setHeader(str,header.get(str));
                }
            }
            HttpResponse res = httpclient.execute(httpPost);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    result = EntityUtils.toString(res.getEntity());
                    //也可以把返回的报文转成json类型
                    // JSONObject  response = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        finally {
             //此处可以加入记录日志的方法
            // 关闭连接,释放资源
           if (httpclient!= null){
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }
        return result;
    }
}

RestTemplate调用

//可以在项目启动类中添加RestTemplate 的bean,后续就可以在代码中@Autowired引入。

@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}

@Slf4j
@Component
public class RestTemplateUtils {
    @Autowired
    private RestTemplate restTemplate;

    /**
     * get 请求 参数在url后面  http://xxxx?aa=xxx&page=0&size=10";
     * @param urls 
     * @return string
     */
    public String doGetRequest(String urls) {
        
        URI uri = UriComponentsBuilder.fromUriString(urls).build().toUri();
        log.info("请求接口:{}", urls);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> httpEntity = new HttpEntity<>(headers);
        //通用的方法exchange,这个方法需要你在调用的时候去指定请求类型,可以是get,post,也能是其它类型的请求
        ResponseEntity<String> responseEntity = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, String.class);
        if (responseEntity == null) {
            return null;
        }
        log.info("返回报文:{}", JSON.toJSONString(responseEntity));
        
        return responseEntity.getBody();
    }
    
    /**
     * post 请求 参数在 request里;
     * @param url, request
     * @return string
     */
    public String doPostRequest(String url, Object request){
        URI uri = UriComponentsBuilder.fromUriString(url).build().toUri();

        String requestStr= JSONObject.toJSONString(request);
        log.info("请求接口:{}, 请求报文:{}", url, requestStr);
        HttpHeaders headers = new HttpHeaders();    
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> httpEntity = new HttpEntity<>(requestStr, headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, String.class);
                
        if (responseEntity == null) {
            return null;
        }
        
        String seqResult = "";
        try {
            if(responseEntity.getBody() != null ) {        
                if(responseEntity.getBody().contains("9001")) {
                    seqResult = new String(responseEntity.getBody().getBytes("ISO8859-1"),"utf-8");
                }else {
                    seqResult = new String(responseEntity.getBody().getBytes(),"utf-8");    
                }                                            
            }
            
            log.info("返回报文:{}", seqResult);
            
        } catch (UnsupportedEncodingException e) {
            log.error("接口返回异常", e);
        }

        return seqResult;
    }
}

总结 

到此这篇关于java对接第三方接口的3种常用方式的文章就介绍到这了,更多相关java对接第三方接口内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • IntelliJ IDEA导入Gradle项目的方法

    IntelliJ IDEA导入Gradle项目的方法

    这篇文章主要介绍了IntelliJ IDEA导入Gradle项目的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-03-03
  • 新手小白学JAVA 日期类Date SimpleDateFormat Calendar(入门)

    新手小白学JAVA 日期类Date SimpleDateFormat Calendar(入门)

    本文主要介绍了JAVA 日期类Date SimpleDateFormat Calendar,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-10-10
  • java编程ThreadLocal上下传递源码解析

    java编程ThreadLocal上下传递源码解析

    这篇文章主要为大家介绍了java编程中ThreadLocal提供的上下传递方式的源码解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步
    2022-03-03
  • Java实现邮箱发送功能实例(阿里云邮箱推送)

    Java实现邮箱发送功能实例(阿里云邮箱推送)

    这篇文章主要给大家介绍了关于Java实现邮箱发送功能的相关资料,利用阿里云邮箱推送,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • Java并发工具之CountDownLatch使用详解

    Java并发工具之CountDownLatch使用详解

    这篇文章主要介绍了Java并发工具之CountDownLatch使用详解,通过使用 CountDownLatch可以使当前线程阻塞,等待其他线程完成给定任务,可以类比旅游团导游要等待所有的游客到齐后才能去下一个景点,需要的朋友可以参考下
    2023-12-12
  • Spring component-scan XML配置与@ComponentScan注解配置

    Spring component-scan XML配置与@ComponentScan注解配置

    这篇文章主要介绍了Spring component-scan XML配置与@ComponentScan注解配置,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-09-09
  • Scala中优雅的处理Null问题

    Scala中优雅的处理Null问题

    Spark 采用混合方式,大部分情况下使用 Option,但个别时候出于性能原因才使用了null。一个很好的习惯是当有方法返回值可能为null的时候,使用Option来代替,本文给大家介绍Scala处理Null的知识详解,一起看看吧
    2021-08-08
  • intellij idea如何将web项目打成war包的实现

    intellij idea如何将web项目打成war包的实现

    这篇文章主要介绍了intellij idea如何将web项目打成war包的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-07-07
  • Java如何分析算法的时间和空间复杂度

    Java如何分析算法的时间和空间复杂度

    这篇文章主要介绍了Java如何分析算法的时间和空间复杂度,在计算机科学中,计算复杂性解释了算法的性能。文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的朋友可以参考一下
    2022-06-06
  • Java中父类强制转换子类问题解决

    Java中父类强制转换子类问题解决

    在Java编程中继承是基础,但父类转换为子类时需谨慎,正确的转换要求父类引用实际指向子类对象,错误转换可能引发ClassCastException,解决方案包括使用instanceof关键字检查、利用泛型避免转换、以及通过多态性避免直接转换,感兴趣的可以了解一下
    2024-11-11

最新评论