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

Retrofit 2如何发送text/xml格式POST请求并获取JSON响应

用Retrofit 2实现SOAP XML POST请求并解析JSON响应

我来帮你搞定这个场景——Retrofit发送SOAP格式的XML POST请求,同时解析JSON格式的响应。其实核心思路就是分开处理请求体的XML构造和响应体的JSON解析,下面是具体步骤和代码示例:

1. 添加必要依赖

首先确保你的项目里引入了Retrofit、Gson转换器(用来解析JSON响应),以及OkHttp(可选但推荐,方便调试)。如果用Gradle的话,在build.gradle里添加:

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:okhttp:4.9.3'
// 可选:添加日志拦截器,方便查看请求响应详情
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.3'

2. 构造SOAP XML请求体

因为要发送XML格式的SOAP请求,我们可以直接构造XML字符串,然后封装成Retrofit需要的RequestBody,注意要设置正确的MediaType(接口文档一般会指定是application/soap+xml还是text/xml):

// 替换成你的实际SOAP请求内容,注意转义双引号
String soapRequestXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
        "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
        "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
        "xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">" +
        "<soap12:Body>" +
        "<YourTargetMethodName>" + // 替换成接口要求的方法名
        "<Param1>your-value-1</Param1>" + // 替换成实际参数
        "<Param2>your-value-2</Param2>" +
        "</YourTargetMethodName>" +
        "</soap12:Body>" +
        "</soap12:Envelope>";

// 创建RequestBody,指定MediaType
RequestBody requestBody = RequestBody.create(
        soapRequestXml,
        MediaType.parse("application/soap+xml; charset=utf-8")
);

如果你的SOAP请求有很多动态参数,硬拼字符串容易出错,也可以用SimpleXml把Java对象序列化成XML字符串:

  • 先添加依赖:implementation 'com.squareup.retrofit2:converter-simplexml:2.9.0'
  • 定义SOAP对应的实体类(比如Envelope、Body、YourRequest),加上SimpleXml的注解
  • 用Serializer把对象转成XML字符串:
Serializer serializer = new Persister();
Envelope envelope = new Envelope();
// 给envelope设置参数...
String soapXml = serializer.write(envelope);

3. 定义Retrofit接口

接口里的POST方法接收我们构造的RequestBody,返回的Call泛型是你根据JSON响应结构生成的实体类(比如YourJsonResponse):

public interface SoapApiService {
    @POST("your-api-endpoint") // 替换成接口的实际路径(baseUrl之外的部分)
    Call<YourJsonResponse> sendSoapRequest(@Body RequestBody requestBody);
}

4. 创建Retrofit实例并发起请求

这里只需要添加GsonConverterFactory来解析JSON响应,请求体我们已经自己处理好了:

// 配置OkHttpClient,添加日志拦截器方便调试
OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .addInterceptor(new HttpLoggingInterceptor()
                .setLevel(HttpLoggingInterceptor.Level.BODY))
        .build();

// 构建Retrofit实例
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://your-api-base-url.com/") // 替换成实际的Base URL
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create()) // 解析JSON响应
        .build();

// 创建接口实例
SoapApiService apiService = retrofit.create(SoapApiService.class);

// 发起异步请求
Call<YourJsonResponse> call = apiService.sendSoapRequest(requestBody);
call.enqueue(new Callback<YourJsonResponse>() {
    @Override
    public void onResponse(Call<YourJsonResponse> call, Response<YourJsonResponse> response) {
        if (response.isSuccessful() && response.body() != null) {
            // 成功拿到JSON响应,处理业务逻辑
            YourJsonResponse jsonResult = response.body();
            // do something...
        } else {
            // 请求失败,打印错误信息
            try {
                Log.e("SOAP_ERROR", "请求失败: " + response.errorBody().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onFailure(Call<YourJsonResponse> call, Throwable t) {
        // 网络异常处理
        t.printStackTrace();
    }
});

关键注意事项

  • MediaType要匹配:务必确认接口要求的Content-Type是application/soap+xml还是text/xml,填错会导致请求被拒绝。
  • JSON实体类要准确:根据接口返回的JSON结构生成对应的Java实体类(可以用GsonFormat等工具自动生成),字段名、类型要完全匹配,否则解析会失败。
  • 调试用日志拦截器:HttpLoggingInterceptor能帮你看到完整的请求XML和响应JSON,方便排查问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:36:26