我在下面有以下 Android 应用程序代码。我正在尝试通过 HTTP 连接到 Web 服务。 Web 服务使用 apache axis。但是,我在响应中遇到错误“读取 XMLStreamReader 时出错”。我真的被困住了,不知道我能做什么。难道是服务器端和客户端使用了不同版本的HTTP客户端和SOAP??对此的任何帮助将不胜感激。 Web 服务非常简单:sayHello 方法显示 arg0=some_string 中给出的参数
public class MainActivity extends Activity {
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(
"http://10.0.0.63:8080/archibus/cxf/HelloWorld/sayHello");
request.addHeader("Content-Type", "text/xml");
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("arg0", "testing"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
// Log.i(tag, page);
System.out.println(page);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
最佳答案
您的 WebService 请求构造不正确。您实际上是在创建表单请求,而不是实际的 SOAP 请求。
SOAP 请求是一个 XML 文档,它有一个信封和一个正文,请参见此处的示例 SOAP Message Example on Wikipedia .
您实际上在这里做的是模拟提交表单的标准 HTTP 调用,而不是 SOAP 调用。
这里有两个解决方案:
1- 您可以通过手动创建 XML 文档并提交来模拟 SOAP 客户端的行为。 除了将正确的 XML 文档设置为请求正文之外,不要忘记设置正确的 header :SOAPAction、Content-Type 和 Content-Length
RequestEntity requestEntity = new StringRequestEntity("<?xml version=\"1.0\"?><soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\"><soap:Header></soap:Header><soap:Body><m:GetStockPrice xmlns:m=\"http://www.example.org/stock\"><m:StockName>IBM</m:StockName></m:GetStockPrice></soap:Body></soap:Envelope>");
post.setRequestEntity(requestEntity );
另外不要忘记将上面的命名空间 (m) 更改为您的网络服务正在使用的正确命名空间。以及包含您尝试调用的操作的操作名称 (GetStockPrice )。也不要忘记参数名称和类型。
2- 您可以使用 Apache Axis 生成客户端并将该客户端用于您的应用程序
查看此线程以获取更多信息和推荐的客户端 How to call a SOAP web service on Android
关于java - SOAP 信封响应错误 : Error reading XMLStreamReader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12568148/