我很难找到有关如何使用Android调用标准SOAP / WSDL Web服务的良好信息。我所能找到的只是非常复杂的文档和对“ kSoap2”的引用,然后是一些有关使用SAX手动解析它们的内容。好的,很好,但是是2008年,所以我认为应该有一些好的库来调用标准Web服务。
Web服务基本上只是在NetBeans中创建的一种。我希望IDE支持生成管道类。我只需要最简单/最优雅的方法就可以从基于Android的电话联系基于WSDL的Web服务。
我很难找到有关如何使用Android调用标准SOAP / WSDL Web服务的良好信息。我所能找到的只是非常复杂的文档和对“ kSoap2”的引用,然后是一些有关使用SAX手动解析它们的内容。好的,很好,但是是2008年,所以我认为应该有一些好的库来调用标准Web服务。
Web服务基本上只是在NetBeans中创建的一种。我希望IDE支持生成管道类。我只需要最简单/最优雅的方法就可以从基于Android的电话联系基于WSDL的Web服务。
Answers:
Android不提供任何类型的SOAP库。您可以编写自己的代码,也可以使用类似kSOAP 2的代码。如您所述,其他人已经能够在自己的项目中编译和使用kSOAP2,但是我不必这样做。
到目前为止,谷歌对将SOAP库添加到Android几乎没有兴趣。我对此表示怀疑,他们宁愿支持Web服务中基于REST服务的当前趋势,并使用JSON作为数据封装格式。或者,使用XMPP进行消息传递。但这只是推测。
目前,基于XML的Web服务在Android上是一项微不足道的任务。不知道NetBeans,我无法谈论那里的可用工具,但是我同意应该有一个更好的库。XmlPullParser可能会使您免于使用SAX,但是我对此并不了解。
org.apache.http.impl.client.DefaultHttpClient
默认情况下包含在Android SDK中。这将使您连接到WSDL。
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://www.example.com/" + URL);
HttpResponse response = httpClient.execute(httpGet, localContext);
确实,由于存在开销,SOAP并不是与移动设备进行数据交换的最佳选择。但是,您可能会发现自己无法控制服务器输出的格式。
因此,如果您必须坚持使用SOAP,请在此处为Android修补一个kSOAP2库:http :
//code.google.com/p/ksoap2-android/
要从移动设备(特别是在Android手机上)调用Web服务,我使用了一种非常简单的方法来实现。我没有使用任何Web服务客户端API来尝试调用Web服务。我的拨打电话的方法如下。
HttpURLConnection
。getResonseCode
)。ErrorInput
在同一HTTPobject上流,并接收错误(如果有)。我已经为Android手机实现了此过程,并且该过程已成功运行。即使超过700 KB,我也可以解析响应。
由于需要处理/解析开销,因此SOAP是不适合在Android(或一般移动设备)上使用的技术。REST服务是一种较轻的解决方案,这就是我的建议。Android随附了SAX解析器,使用起来相当简单。如果绝对需要您在移动设备上处理/解析SOAP,那么我为您感到抱歉,我能提供的最佳建议就是不要使用SOAP。
大约一年前,我正在阅读此主题,试图弄清楚如何在Android上进行SOAP调用-使用HttpClient构建自己的SOAP的建议导致我为Android构建了自己的SOAP库:
基本上,它允许您建立信封以通过简单的Java API发送,然后自动将其解析为您通过XPath定义的对象...例如:
<Dictionary>
<Id></Id>
<Name></Name>
</Dictionary>
成为:
@XMLObject("//Dictionary")
public class Dictionary {
@XMLField("Id")
private String id;
@XMLField("Name")
private String name;
}
我在自己的项目中使用了它,但是我发现它可能会对其他人有所帮助,因此我花了一些时间将其分离出来并进行记录。如果您的一些可怜的人在谷歌搜索“ SOAP Android”时偶然发现了这个线程,我真的会喜欢它,并且可以从中受益。
不要忘记在项目中添加ksoap2.jar并在AndroidManifest文件中添加INTERNET权限
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class WebserviceActivity extends Activity {
private static final String NAMESPACE = "https://api.authorize.net/soap/v1/";
private static final String URL ="https://apitest.authorize.net/soap/v1/Service.asmx?wsdl";
private static final String SOAP_ACTION = "https://api.authorize.net/soap/v1/AuthenticateTest";
private static final String METHOD_NAME = "AuthenticateTest";
private TextView lblResult;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lblResult = (TextView) findViewById(R.id.tv);
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("name","44vmMAYrhjfhj66fhJN");
request.addProperty("transactionKey","9MDQ7fghjghjh53H48k7e7n");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
//SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();
// SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();
SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
lblResult.setText(resultsRequestSOAP.toString());
System.out.println("Response::"+resultsRequestSOAP.toString());
} catch (Exception e) {
System.out.println("Error"+e);
}
}
}
您可以看一下WSClient ++
我为Android平台创建了一个新的SOAP客户端。它使用的是JAX-WS生成的接口,但是到目前为止,这只是概念验证。
如果您有兴趣,请尝试示例和/或观看AndroidSOAP上的源代码。
调用ksoap2方法。它工作得很好。
设置详细信息,例如
private static String mNAMESPACE=null;
private static String mURL=null;
public static Context context=null;
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(Request);
envelope.addMapping(mNAMESPACE, "UserCredentials",new UserCredendtials().getClass());
AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(mURL);
然后得到结果
androidHttpTransport.call(SOAP_ACTION, envelope);
result = (SoapPrimitive)envelope.getResponse();
我希望从Android调用网络服务会有所帮助。
几个月前,我在j2ee应用程序中使用jax-ws Web服务,我们在使用CXF wsdl2java从WSDL文件生成WS客户端存根,并使用这些客户端存根消耗了Web服务。几周前,当我试图以相同的方式在android平台中使用Web服务时,我做不到,因为android jar中没有所有的“ jax-ws”支持类。那个时候,我没有找到任何可以满足我的要求的工具(如果我没有失败地使用Google的话)
因此,我开发了自己的Android SOAP客户端生成工具。您必须按照以下步骤操作:
例如:
ComplexOperationService service = new ComplexOperationService( );
ComplexOperation port= service.getComplexOperationPort();
SomeComplexRequest request = --Get some complex request----;
SomeComplexResp resp = port.operate( request );
我认为从Android应用程序调用SOAP Web服务 将对您有很大帮助。
如果可以使用JSON,则在使用PHP服务器和Android Phone客户端开发应用程序服务中有白皮书,视频和sample.code 。
如果您在使用android调用Web服务时遇到问题,则可以使用以下代码来调用Web服务并获得响应。确保您的Web服务以数据表格式返回响应。如果您使用SQL Server数据库中的数据,则此代码将为您提供帮助。如果您使用MYSQL,则需要更改一件事,只需用DocumentElement替换句子中的单词 NewDataSetobj2=(SoapObject) obj1.getProperty("NewDataSet");
void callWebService(){
private static final String NAMESPACE = "http://tempuri.org/"; // for wsdl it may be package name i.e http://package_name
private static final String URL = "http://localhost/sample/services/MyService?wsdl";
// you can use IP address instead of localhost
private static final String METHOD_NAME = "Function_Name";
private static final String SOAP_ACTION = "urn:" + METHOD_NAME;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("parm_name", prm_value);// Parameter for Method
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;// **If your Webservice in .net otherwise remove it**
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);// call the eb service
// Method
} catch (Exception e) {
e.printStackTrace();
}
// Next task is to get Response and format that response
SoapObject obj, obj1, obj2, obj3;
obj = (SoapObject) envelope.getResponse();
obj1 = (SoapObject) obj.getProperty("diffgram");
obj2 = (SoapObject) obj1.getProperty("NewDataSet");
for (int i = 0; i < obj2.getPropertyCount(); i++) {
// the method getPropertyCount() and return the number of rows
obj3 = (SoapObject) obj2.getProperty(i);
obj3.getProperty(0).toString();// value of column 1
obj3.getProperty(1).toString();// value of column 2
// like that you will get value from each column
}
}
如果对此有任何疑问,可以给我写信。
请下载并添加带有您的项目的SOAP库文件文件名:ksoap2-android-assembly-3.4.0-jar-with-dependencies
清理应用程序,然后启动程序
这是SOAP服务调用的代码
String SOAP_ACTION = "YOUR_ACTION_NAME";
String METHOD_NAME = "YOUR_METHOD_NAME";
String NAMESPACE = "YOUR_NAME_SPACE";
String URL = "YOUR_URL";
SoapPrimitive resultString = null;
try {
SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
addPropertyForSOAP(Request);
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(Request);
HttpTransportSE transport = new HttpTransportSE(URL);
transport.call(SOAP_ACTION, soapEnvelope);
resultString = (SoapPrimitive) soapEnvelope.getResponse();
Log.i("SOAP Result", "Result Celsius: " + resultString);
} catch (Exception ex) {
Log.e("SOAP Result", "Error: " + ex.getMessage());
}
if(resultString != null) {
return resultString.toString();
}
else{
return "error";
}
结果可能是JSONObject或JSONArray或String
供您更好的参考, https://trinitytuts.com/load-data-from-soap-web-service-in-android-application/
谢谢。
这是在Android中使用SOAP Web服务的工作示例。
**注意:: ***不要忘记在项目中添加ksoap2.jar并在AndroidManifest文件中添加INTERNET权限*
public final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
public final String METHOD_NAME = "FahrenheitToCelsius";
public final String PROPERTY_NAME = "Fahrenheit";
public final String SOAP_ACTION = "http://tempuri.org/FahrenheitToCelsius";
public final String SOAP_ADDRESS = "http://www.w3schools.com/webservices/tempconvert.asmx";
private class TestAsynk extends AsyncTask<String, Void, String> {
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(),
String.format("%.2f", Float.parseFloat(result)),
Toast.LENGTH_SHORT).show();
}
@Override
protected String doInBackground(String... params) {
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
METHOD_NAME);
request.addProperty(PROPERTY_NAME, params[0]);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
SOAP_ADDRESS);
Object response = null;
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
response = envelope.getResponse();
Log.e("Object response", response.toString());
} catch (Exception e) {
e.printStackTrace();
}
return response.toString();
}
}
您可以使用某些标头通过HTTP进行肥皂呼叫。我没有使用ksoap2之类的其他库就解决了这个问题,这是从soap服务获取订单的实时代码
private static HashMap<String,String> mHeaders = new HashMap<>();
static {
mHeaders.put("Accept-Encoding","gzip,deflate");
mHeaders.put("Content-Type", "application/soap+xml");
mHeaders.put("Host", "35.15.85.55:8080");
mHeaders.put("Connection", "Keep-Alive");
mHeaders.put("User-Agent","AndroidApp");
mHeaders.put("Authorization","Basic Q2xpZW50NTkzMzppMjR3s2U="); // optional
}public final static InputStream receiveCurrentShipments(String stringUrlShipments)
{
int status=0;
String xmlstring= "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:ser=\"http://35.15.85.55:8080/ServiceTransfer\">\n" +
" <soap:Header/>\n" +
" <soap:Body>\n" +
" <ser:GetAllOrdersOfShipment>\n" +
" <ser:CodeOfBranch></ser:CodeOfBranch>\n" +
" </ser:GetAllOrdersOfShipment>\n" +
" </soap:Body>\n" +
"</soap:Envelope>";
StringBuffer chaine = new StringBuffer("");
HttpURLConnection connection = null;
try {
URL url = new URL(stringUrlShipments);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Length", xmlstring.getBytes().length + "");
connection.setRequestProperty("SOAPAction", "http://35.15.85.55:8080/ServiceTransfer/GetAllOrdersOfShipment");
for(Map.Entry<String, String> entry : mHeaders.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
connection.setRequestProperty(key,value);
}
connection.setRequestMethod("POST");
connection.setDoInput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(xmlstring.getBytes("UTF-8"));
outputStream.close();
connection.connect();
status = connection.getResponseCode();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
Log.i("HTTP Client", "HTTP status code : " + status);
}
InputStream inputStream = null;
try {
inputStream = connection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return inputStream;
}
要从android调用SOAP Web服务,请尝试使用此客户端
不要忘记在Java构建路径中添加ksoap2-android.jar
public class WsClient {
private static final String SOAP_ACTION = "somme";
private static final String OPERATION_NAME = "somme";
private static final String WSDL_TARGET_NAMESPACE = "http://example.ws";
private static final String SOAP_ADDRESS = "http://192.168.1.2:8080/axis2/services/Calculatrice?wsdl";
public String caclculerSomme() {
String res = null;
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
OPERATION_NAME);
request.addProperty("a", "5");
request.addProperty("b", "2");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
try {
httpTransport.call(SOAP_ACTION, envelope);
String result = envelope.getResponse().toString();
res = result;
System.out.println("############# resull is :" + result);
} catch (Exception exception) {
System.out.println("########### ERRER" + exception.getMessage());
}
return res;
}
}
添加肥皂Libaray(ksoap2-android-assembly-3.2.0-jar-with-dependencies.jar
):
公共静态字符串Fn_Confirm_CollectMoney_Approval(
HashMap < String, String > str1,
HashMap < String, String > str2,
HashMap < String, String > str3) {
Object response = null;
String METHOD_NAME = "CollectMoney";
String NAMESPACE = "http://xxx/yyy/xxx";
String URL = "http://www.w3schools.com/webservices/tempconvert.asmx";
String SOAP_ACTION = "";
try {
SoapObject RequestParent = new SoapObject(NAMESPACE, METHOD_NAME);
SoapObject Request1 = new SoapObject(NAMESPACE, "req");
PropertyInfo pi = new PropertyInfo();
Set mapSet1 = (Set) str1.entrySet();
Iterator mapIterator1 = mapSet1.iterator();
while (mapIterator1.hasNext()) {
Map.Entry mapEntry = (Map.Entry) mapIterator1.next();
String keyValue = (String) mapEntry.getKey();
String value = (String) mapEntry.getValue();
pi = new PropertyInfo();
pi.setNamespace("java:com.xxx");
pi.setName(keyValue);
pi.setValue(value);
Request1.addProperty(pi);
}
mapSet1 = (Set) str3.entrySet();
mapIterator1 = mapSet1.iterator();
while (mapIterator1.hasNext()) {
Map.Entry mapEntry = (Map.Entry) mapIterator1.next();
// getKey Method of HashMap access a key of map
String keyValue = (String) mapEntry.getKey();
// getValue method returns corresponding key's value
String value = (String) mapEntry.getValue();
pi = new PropertyInfo();
pi.setNamespace("java:com.xxx");
pi.setName(keyValue);
pi.setValue(value);
Request1.addProperty(pi);
}
SoapObject HeaderRequest = new SoapObject(NAMESPACE, "XXX");
Set mapSet = (Set) str2.entrySet();
Iterator mapIterator = mapSet.iterator();
while (mapIterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) mapIterator.next();
// getKey Method of HashMap access a key of map
String keyValue = (String) mapEntry.getKey();
// getValue method returns corresponding key's value
String value = (String) mapEntry.getValue();
pi = new PropertyInfo();
pi.setNamespace("java:com.xxx");
pi.setName(keyValue);
pi.setValue(value);
HeaderRequest.addProperty(pi);
}
Request1.addSoapObject(HeaderRequest);
RequestParent.addSoapObject(Request1);
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
SoapEnvelope.VER10);
soapEnvelope.dotNet = false;
soapEnvelope.setOutputSoapObject(RequestParent);
HttpTransportSE transport = new HttpTransportSE(URL, 120000);
transport.debug = true;
transport.call(SOAP_ACTION, soapEnvelope);
response = (Object) soapEnvelope.getResponse();
int cols = ((SoapObject) response).getPropertyCount();
Object objectResponse = (Object) ((SoapObject) response)
.getProperty("Resp");
SoapObject subObject_Resp = (SoapObject) objectResponse;
modelObject = new ResposeXmlModel();
String MsgId = subObject_Resp.getProperty("MsgId").toString();
modelObject.setMsgId(MsgId);
String OrgId = subObject_Resp.getProperty("OrgId").toString();
modelObject.setOrgId(OrgId);
String ResCode = subObject_Resp.getProperty("ResCode").toString();
modelObject.setResCode(ResCode);
String ResDesc = subObject_Resp.getProperty("ResDesc").toString();
modelObject.setResDesc(ResDesc);
String TimeStamp = subObject_Resp.getProperty("TimeStamp")
.toString();
modelObject.setTimestamp(ResDesc);
return response.toString();
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}