You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Retrofit发送指定POST请求并获取响应

使用Retrofit发送指定POST请求的步骤

1. 添加依赖

在Module级别的build.gradle中添加Retrofit及相关依赖:

dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.okhttp3:okhttp:4.9.3'
    // 如需解析XML响应,添加XML转换器
    implementation 'com.squareup.retrofit2:converter-simplexml:2.9.0'
}

2. 定义Retrofit接口

创建接口类,匹配请求的URL、请求头及请求体规则:

import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;

public interface SonyIrccApi {
    @Headers({
        "Accept: */*",
        "Content-Type: text/xml; charset=UTF-8",
        "SOAPACTION: \"urn:schemas-sony-com:service:IRCC:1#X_SendIRCC\"",
        "X-Auth-PSK: 1234",
        "Connection: Keep-Alive"
    })
    @POST("/sony/ircc")
    Call<String> sendIrccCommand(@Body String requestBody);
}

注:若需将XML响应解析为实体类,可把Call<String>替换为对应实体类的Call<YourResponseModel>,并确保已配置XML转换器。

3. 构建Retrofit实例并发送请求

初始化Retrofit,创建接口实例后发起请求:

import retrofit2.Retrofit;
import retrofit2.Response;

public class RequestDemo {
    public static void main(String[] args) throws Exception {
        // 构建Retrofit实例
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.0.1/")
                .build();

        // 创建API接口实例
        SonyIrccApi api = retrofit.create(SonyIrccApi.class);

        // 构造请求体XML字符串
        String requestBody = "<s:Envelope\n" +
                "    xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" +
                "    s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n" +
                "    <s:Body>\n" +
                "        <u:X_SendIRCC xmlns:u=\"urn:schemas-sony-com:service:IRCC:1\">\n" +
                "            <IRCCCode>AAAAAQAAAAEAAAB1Aw==</IRCCCode>\n" +
                "        </u:X_SendIRCC>\n" +
                "    </s:Body>\n" +
                "</s:Envelope>";

        // 同步请求(会阻塞当前线程)
        Response<String> response = api.sendIrccCommand(requestBody).execute();

        // 处理响应结果
        if (response.isSuccessful()) {
            System.out.println("请求成功,响应内容:" + response.body());
        } else {
            System.out.println("请求失败,错误码:" + response.code() + ",错误信息:" + response.errorBody().string());
        }
    }
}

4. 异步请求处理(可选)

若要避免主线程阻塞,使用异步请求方式:

api.sendIrccCommand(requestBody).enqueue(new retrofit2.Callback<String>() {
    @Override
    public void onResponse(Call<String> call, Response<String> response) {
        if (response.isSuccessful()) {
            // 处理成功响应逻辑
        } else {
            // 处理错误响应逻辑
        }
    }

    @Override
    public void onFailure(Call<String> call, Throwable t) {
        // 处理网络异常等请求失败情况
        t.printStackTrace();
    }
});

内容的提问来源于stack exchange,提问作者WilliamVietnam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 04:42:35