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

Android中如何调用带参数的SOAP WebService?

在Android中调用带参数SOAP WebService的替代方法

如果你试过Retrofit、OkHttp、ksoap2都没成功,可以试试以下几种方案:

1. 用原生HttpURLConnection手动实现

不需要依赖任何第三方库,完全手动构建SOAP请求并解析响应,适合排查格式匹配问题。

Java示例:

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

public class SoapWebServiceCall {
    public static void callSoapService() {
        try {
            // 替换为你的WebService端点URL
            URL url = new URL("http://your-webservice-endpoint.com/Service.asmx");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            
            // 设置请求头
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            // 替换为服务要求的SOAPAction值
            conn.setRequestProperty("SOAPAction", "http://your-namespace/YourMethodName");
            
            // 构建符合服务要求的SOAP请求体,替换命名空间、方法名和参数
            String soapEnvelope = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:your=\"http://your-namespace/\">"
                    + "<soapenv:Header/>"
                    + "<soapenv:Body>"
                    + "<your:YourMethodName>"
                    + "<your:Param1>value1</your:Param1>"
                    + "<your:Param2>value2</your:Param2>"
                    + "</your:YourMethodName>"
                    + "</soapenv:Body>"
                    + "</soapenv:Envelope>";
            
            // 发送请求
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            os.write(soapEnvelope.getBytes("UTF-8"));
            os.flush();
            os.close();
            
            // 读取响应
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = br.readLine()) != null) {
                response.append(line);
            }
            br.close();
            
            // 解析响应XML,可使用XmlPullParser或第三方XML解析库处理结果
            String result = response.toString();
            
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Kotlin示例:

import java.net.HttpURLConnection
import java.net.URL

fun callSoapService() {
    try {
        val url = URL("http://your-webservice-endpoint.com/Service.asmx")
        val conn = url.openConnection() as HttpURLConnection
        
        conn.requestMethod = "POST"
        conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8")
        conn.setRequestProperty("SOAPAction", "http://your-namespace/YourMethodName")
        
        val soapEnvelope = """
            <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:your="http://your-namespace/">
                <soapenv:Header/>
                <soapenv:Body>
                    <your:YourMethodName>
                        <your:Param1>value1</your:Param1>
                        <your:Param2>value2</your:Param2>
                    </your:YourMethodName>
                </soapenv:Body>
            </soapenv:Envelope>
        """.trimIndent()
        
        conn.doOutput = true
        conn.outputStream.use { os ->
            os.write(soapEnvelope.toByteArray(Charsets.UTF_8))
            os.flush()
        }
        
        val response = conn.inputStream.bufferedReader().use { it.readText() }
        // 解析响应XML并处理结果
        
        conn.disconnect()
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

注意:必须确保SOAP信封的命名空间、方法名、参数名与WebService的WSDL定义完全一致,SOAPAction头也不能写错(部分服务可能不需要,但多数场景下是必填项)。

2. 使用Apache HttpClient兼容库

Android 6.0后移除了原生Apache HttpClient,但可通过导入第三方兼容库使用,其API比HttpURLConnection更简洁。

首先在build.gradle中添加依赖:

dependencies {
    implementation 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
}

Java示例:

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class ApacheHttpClientSoapCall {
    public static void callService() {
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://your-webservice-endpoint.com/Service.asmx");
            
            httpPost.setHeader("Content-Type", "text/xml; charset=utf-8");
            httpPost.setHeader("SOAPAction", "http://your-namespace/YourMethodName");
            
            String soapEnvelope = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:your=\"http://your-namespace/\">"
                    + "<soapenv:Header/>"
                    + "<soapenv:Body>"
                    + "<your:YourMethodName>"
                    + "<your:Param1>value1</your:Param1>"
                    + "<your:Param2>value2</your:Param2>"
                    + "</your:YourMethodName>"
                    + "</soapenv:Body>"
                    + "</soapenv:Envelope>";
            
            StringEntity entity = new StringEntity(soapEnvelope, "UTF-8");
            httpPost.setEntity(entity);
            
            HttpResponse response = httpClient.execute(httpPost);
            String responseString = EntityUtils.toString(response.getEntity());
            
            // 解析响应XML并处理结果
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3. 使用轻量SOAP客户端库(Simple SOAP Client)

该库专为Android设计,可简化SOAP请求构建与响应解析,无需手动拼接XML。

添加依赖到build.gradle:

dependencies {
    implementation 'com.github.codekidX:simple-soap-client:1.4.5'
}

Kotlin示例:

import com.codekidlabs.storagechooser.soapclient.SoapClient
import com.codekidlabs.storagechooser.soapclient.SoapEnvelope

fun callSoapWithLibrary() {
    val client = SoapClient.Builder()
        .setEndpoint("http://your-webservice-endpoint.com/Service.asmx")
        .setSoapAction("http://your-namespace/YourMethodName")
        .setEnvelope(SoapEnvelope.VER11) // 根据服务SOAP版本选择VER11或VER12
        .build()
    
    // 添加对应参数
    client.addParameter("Param1", "value1")
    client.addParameter("Param2", "value2")
    
    // 发送请求并处理结果
    client.call("YourMethodName", object : SoapClient.Callback {
        override fun onResponse(response: String) {
            // 解析响应XML并处理
        }
        
        override fun onError(error: String) {
            // 处理请求错误
        }
    })
}

提示:无论用哪种方法,建议先通过Postman或SoapUI测试WebService的请求格式是否正确,确认参数、命名空间、SOAPAction均无误后,再移植到Android代码中,可大幅降低排查难度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 11:27:41