实现get/post请求调用第三方接口

1 篇文章 0 订阅
使用http协议中的get以及post方式对接第三方平台在工作中很常见,我所展示的已是将方法归纳好,只需要按照对接方案传递对应的参数即可。

下载地址 https://download.csdn.net/download/qq_48856537/86266035?spm=1003.2166.3001.6637.1=

post对接第三方接口

  1. 通常post协议传参大多数都是通过请求体来实现参数传递,如图所示,将对应数据进行处理实现传参。

  2. post方式的基础工具类如下所示:

get对接第三方接口

  1. get方式的基础工具类如下所示:
Java可以使用HttpURLConnection或者HttpClient等类库来实现调用第三方API的GET和POST请求GET请求示例: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class GetRequestExample { public static void main(String[] args) { try { URL url = new URL("https://api.example.com/data"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` POST请求示例: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.io.OutputStream; import java.nio.charset.StandardCharsets; public class PostRequestExample { public static void main(String[] args) { try { URL url = new URL("https://api.example.com/data"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setDoOutput(true); String requestBody = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"; try (OutputStream os = conn.getOutputStream()) { byte[] input = requestBody.getBytes(StandardCharsets.UTF_8); os.write(input, 0, input.length); } if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 这里以调用JSON格式的API接口为例,请求头中设置了Accept为"application/json",请求体中的数据也是JSON格式的。POST请求需要设置请求方法为"POST",同时需要设置请求头中的Content-Type为"application/json",并且需要将请求体数据写入到请求输出流中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值