[英]Calling Soap webservice from android
我正在使用以下流程,
1)为SOAP请求创建String模板,并在此模板中在运行时替换用户提供的值以创建有效请求。 2)将此字符串包装在StringEntity中,并将其内容类型设置为text / xml 3)在SOAP请求中设置此实体。
在httppost的帮助下,我发布了请求,
我正在使用w3schools.com的演示网络服务
网址--->
http://www.w3schools.com/webservices/tempconvert.asmx
我试过的是,
HttpPost httppost = new HttpPost("http://www.w3schools.com/webservices/tempconvert.asmx");
StringEntity se;
try {
SOAPRequestXML="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\"><soapenv:Header/><soapenv:Body><tem:CelsiusToFahrenheit><!--Optional:--><tem:Celsius>30</tem:Celsius></tem:CelsiusToFahrenheit></soapenv:Body></soapenv:Envelope>";
Log.d("request is ", SOAPRequestXML+"!!!");
se = new StringEntity(SOAPRequestXML,HTTP.UTF_8);
se.setContentType("text/xml");
httppost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
httppost.setEntity(se);
HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse =
(BasicHttpResponse) httpclient.execute(httppost);
HttpEntity resEntity = httpResponse.getEntity();
t.setText(EntityUtils.toString(resEntity));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
我能够在soapui中得到响应,所以代码肯定是错误的,因为在模拟器中我得到了输出,
“服务器无法为请求提供服务,因为媒体类型不受支持”。
我是否在HttpPost的构造函数中传递了正确的参数,或者我正在制作正确的xml请求。我尝试了很多但是无法弄明白。
谢谢
您的代码唯一的问题是您将Header设置为,
httppost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
代替,
httppost.setHeader("Content-Type", "text/xml;charset=UTF-8");
正如您在URL中看到的请求 - > w3schoools ,他们正在使用,
Content-Type: text/xml; charset=utf-8
而你没有传递相同的内容类型。 所以,它给你的错误,因为,
服务器无法为请求提供服务,因为不支持媒体类型。
因此,只需更改标题即可获得所需的响应。
我在c-sharpcorner.com上写了一篇关于如何在Android中使用SOAP调用Web服务的文章。
这篇文章让很多人得到了帮助。 您也可以下载并运行。 我将帮助您了解如何使用SOAP进行Web服务。
编辑
看看以下链接。 它使用ksoap进行复杂的数据处理。
我有预感,模拟器的Android版本和手机版本是不同的。
但我提出的建议很少。 使用以下:
httppost.setHeader("Accept-Charset","utf-8");
httppost.setHeader("Accept","text/xml,application/text+xml,application/soap+xml");
类似地,将内容类型设置为以上所有。
这样,html表单发布了123摄氏度。 没有SOAP或信封,只是工作:)
try {
HttpPost httppost = new HttpPost("http://www.w3schools.com/webservices/tempconvert.asmx/CelsiusToFahrenheit");
StringEntity se = new StringEntity("Celsius=123");
httppost.setEntity(se);
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse httpResponse = new DefaultHttpClient().execute(httppost);
HttpEntity resEntity = httpResponse.getEntity();
return EntityUtils.toString(resEntity);
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.