HttpURLConnection实现

c 复制代码
我有一个接口 http://ip:port/Others/airportnew/,采用post方法调用,采用body方式传值,其body内容为{
    "data": {
        "data": {
            "image": ""
        }
    }
},现在我需要在java中调用这个接口,帮我写调用方法和测试的main方法

以下是一个使用Java调用该接口的完整示例,包括HttpURLConnection实现和测试main方法:

java 复制代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class AirportApiCaller {

    // 调用接口的核心方法
    public static String callAirportApi(String apiUrl, String jsonInput) throws IOException {
        // 创建URL对象
        URL url = new URL(apiUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        
        try {
            // 设置请求参数
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);
            connection.setConnectTimeout(5000);  // 5秒连接超时
            connection.setReadTimeout(10000);   // 10秒读取超时
            
            // 发送请求体
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInput.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
            
            // 获取响应代码
            int responseCode = connection.getResponseCode();
            
            // 读取响应内容
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(
                        (responseCode == HttpURLConnection.HTTP_OK) ? 
                        connection.getInputStream() : connection.getErrorStream(), 
                        StandardCharsets.UTF_8))) {
                
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                
                // 返回响应结果(包含状态码和内容)
                return String.format("HTTP %d: %s", responseCode, response.toString());
            }
        } finally {
            connection.disconnect(); // 确保断开连接
        }
    }

    public static void main(String[] args) {
        // 接口地址
        String apiUrl = "http://ip:port/Others/airportnew/";
        
        // 构建JSON请求体
        String jsonBody = "{\"data\":{\"data\":{\"image\":\"\"}}}";
        
        try {
            System.out.println("正在调用机场接口...");
            String response = callAirportApi(apiUrl, jsonBody);
            System.out.println("接口响应: " + response);
        } catch (IOException e) {
            System.err.println("调用接口时发生错误:");
            e.printStackTrace();
        }
    }
}

使用说明:

  1. 核心方法callAirportApi

    • 接收API地址和JSON请求体
    • 设置正确的HTTP头(Content-Type: application/json)
    • 处理请求和响应流
    • 返回包含状态码和响应内容的字符串
  2. 测试方法

    • 在main方法中直接提供接口URL和请求体
    • 自动处理成功/失败的响应
    • 包含基本的错误处理

可能的响应处理:

如果接口返回403错误(如之前问题所述),你可能需要添加认证信息。以下是添加认证头的修改示例:

java 复制代码
// 在设置请求头的部分添加认证信息
connection.setRequestProperty("Authorization", "Bearer your_token_here");
// 或者
connection.setRequestProperty("x-ais-token", "your_token_value");

依赖说明:

  • 纯Java标准库实现(java.net包),无需额外依赖
  • 兼容Java 8及以上版本

常见问题排查:

  1. 如果遇到连接超时:

    • 检查IP/端口是否可达(使用 telnet 172.22.1.65 8088 测试)
    • 调整 setConnectTimeout()setReadTimeout()
  2. 如果返回403:

    • 检查是否需要添加认证头(如x-ais-token)
    • 确认服务器IP白名单设置
  3. 如果JSON格式错误:

    • 使用在线JSON校验工具检查 jsonBody 格式
    • 确保没有中文引号等非法字符

建议先用Postman测试确保接口可用,再用此Java代码集成到你的应用中。

相关推荐
yaoxin5211235 小时前
434. Java 日期时间 API - Period 基于日期的时间段
java·开发语言·python
何极光6 小时前
IDEA集成Maven
java·maven·intellij-idea
程序员二叉7 小时前
【JUC】ThreadLocal底层原理|内存泄漏|弱引用|跨线程传递方案
java·开发语言·面试·职场和发展·juc
程序员二叉7 小时前
【JUC】线程池全套深度详解|参数|流程|拒绝策略|调优|异常处理
java·开发语言·jvm·算法·面试·juc
老马识途2.07 小时前
在AI的帮助下理解spring的启动过程
java·前端·spring
青山木7 小时前
Hot 100 --- 轮转数组
java·数据结构·算法
Qt程序员7 小时前
掌握 Linux 内核调度:从原理到实现(进程篇)
java·开发语言
code bean7 小时前
【LangChain】检索器完全指南:从向量检索到生产级 RAG 架构
java·开发语言·微服务
大白菜和MySQL8 小时前
java应用排查高线程
java·python
KobeSacre8 小时前
ReentrantLock源码
java