java对接第三方接口

一,通过JDK网络类Java.net.HttpURLConnection

使用步骤:

1、通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection)。

2、设置请求的参数。

3、发送请求。

4、以输入流的形式获取返回内容。

5、关闭输入流。

public String sendByPost(String path, String postContent, String authorization) {
    HttpURLConnection httpURLConnection = null;
    BufferedWriter writer = null;
    BufferedReader reader = null;
    
    try {
        URL url = new URL(path);
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setConnectTimeout(20 * 60 * 1000);
        httpURLConnection.setReadTimeout(20 * 60 * 1000);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        httpURLConnection.setRequestProperty("Access-Token", authorization);

        writer = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8"));
        writer.write(postContent);
        writer.flush();

        int httpRspCode = httpURLConnection.getResponseCode();
        InputStream inputStream = (httpRspCode == 200) 
            ? httpURLConnection.getInputStream() 
            : httpURLConnection.getErrorStream();

        reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }

        return sb.toString();
    } catch (Exception e) {
        e.printStackTrace(); 
        return null;
    } finally {
       
        try {
            if (writer != null) writer.close();
            if (reader != null) reader.close();
            if (httpURLConnection != null) httpURLConnection.disconnect();
        } catch (IOException e) {
            e.printStackTrace(); 
        }
    }
}

二,Spring提供的RestTemplate

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

@SpringBootApplication
@MapperScan("com.xxx.xxx.mapper")
public class RiskApplication {


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


    public static void main(String[] args) {
        SpringApplication.run(RiskApplication.class, args);
    }

}
@Autowired
    private RestTemplate restTemplate;


    /**
     * post 请求 参数在 request里;
     * @param url, request
     * @return string
     */
    public String doPostRequest(String url, String  request,String authorization){
        URI uri = UriComponentsBuilder.fromUriString(url).build().toUri();

        // 假如 request 已经是 JSON 字符串,无需再次转换
        // String requestStr= JSONObject.toJSONString(request);
        String requestStr = request; // 直接使用 request

        log.info("请求接口:{}, 请求报文:{}", url, requestStr);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
//        headers.set("Access-Token", authorization);
        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 ) {
                seqResult = responseEntity.getBody();
            }

            log.info("返回报文:{}", seqResult);

        } catch (Exception e) {
            log.error("接口返回异常", e);
        }

        return seqResult;
    }

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值