首页 > 基础资料 博客日记

Java中调用第三方接口的详细指南

2024-08-08 15:00:06基础资料围观192

文章Java中调用第三方接口的详细指南分享给大家,欢迎收藏Java资料网,专注分享技术知识

在Java开发中,经常需要调用第三方接口来获取数据或执行某些服务。本文将详细介绍如何使用Java调用第三方接口,包括使用JDK自带的HttpURLConnection类和流行的第三方库如OkHttp和Apache HttpClient。

一、使用HttpURLConnection调用第三方接口

1. GET请求示例

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class ThirdPartyApiCaller {

    public static void main(String[] args) {
        try {
            // 创建URL对象
            URL url = new URL("https://api.example.com/data");

            // 创建HttpURLConnection对象
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为GET
            connection.setRequestMethod("GET");

            // 发送请求并获取响应码
            int responseCode = connection.getResponseCode();

            // 检查响应码
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应内容
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                // 处理响应内容
                System.out.println(response.toString());
            } else {
                // 处理错误响应
                System.out.println("请求失败,响应码: " + responseCode);
            }

            // 关闭连接
            connection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2. POST请求示例

import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class ThirdPartyApiCaller {

    public static void main(String[] args) {
        try {
            // 创建URL对象
            URL url = new URL("https://api.example.com/submit");

            // 创建HttpURLConnection对象
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");

            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/json");

            // 启用输出流
            connection.setDoOutput(true);

            // 创建请求体
            String requestBody = "{\"key\":\"value\"}";

            // 将请求体写入输出流
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.write(requestBody.getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
            outputStream.close();

            // 发送请求并获取响应码
            int responseCode = connection.getResponseCode();

            // 检查响应码
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应内容
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                // 处理响应内容
                System.out.println(response.toString());
            } else {
                // 处理错误响应
                System.out.println("请求失败,响应码: " + responseCode);
            }

            // 关闭连接
            connection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

二、使用OkHttp库调用第三方接口

OkHttp是一个强大的HTTP客户端库,用于发送和接收HTTP请求。以下是如何使用OkHttp发送POST请求的示例:

import okhttp3.*;
import java.io.IOException;

public class OkHttpExample {

    public static void main(String[] args) throws IOException {
        OkHttpClient client = new OkHttpClient();

        String url = "https://api.example.com/submit";
        String json = "{\"key\":\"value\"}";

        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(json, JSON);



文章来源:https://blog.csdn.net/weixin_65837469/article/details/140498022
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐

标签云