我在Android studio上运行此代码:
MainActivity.java
package myname.company.com.soap__03;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
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", "server:port");
mHeaders.put("Connection", "Keep-Alive");
mHeaders.put("User-Agent", "AndroidApp");
// mHeaders.put("Authorization", "Basic Q2xpZW50NTkzMzppMjR3s2U="); // optional
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
Button openButton = (Button) findViewById(R.id.open);
openButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
receiveCurrentShipments("WSDL URL");
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}catch(Exception e) {
e.printStackTrace();
}
}
public final static InputStream receiveCurrentShipments(String stringUrlShipments) {
int status = 0;
String xmlstring = "<soapenv:Envelope xmlns:soapenv=\"http://someurl\" "+
"xmlns:soap=\"someurl\" "+
"xmlns:gen=\"http://someurl\"> "+
"<soapenv:Header> "+
"<auth:EventID xmlns:auth='http://someurl'>3000</auth:EventID> "+
"</soapenv:Header> "+
"<soapenv:Body> "+
"<gen:getGenericResult> "+
"<Request> "+
"<dataItem> "+
"<name>Username</name> "+
"<type>String</type> "+
"<value>usernamehere</value> "+
"</dataItem> "+
"<dataItem> "+
"<name>Password</name> "+
"<type>String</type> "+
"<value>passwordhere</value> "+
"</dataItem> "+
"</Request> "+
"</gen:getGenericResult> "+
"</soapenv:Body> "+
"</soapenv: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://NAMESPACE\METHOD_NAME");
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;
}
}
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical"
android:padding="16dp">
<Button
android:id="@+id/open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="@color/colorPrimaryDark"
android:elevation="4dp"
android:paddingLeft="70dp"
android:paddingRight="70dp"
android:text="Soap Call"
android:textColor="#fff" />
</LinearLayout>
以下是我的输出:
02/28 14:33:49:启动应用程序 冷交换变化。 $ adb shell am start -n“mokhethea.vodacom.com.soap__03 / myname.company.com.soap__03.MainActivity”-a android.intent.action.MAIN -c android.intent.category.LAUNCHER 已连接到设备上的进程30654 vodafone-vfd_500-TK8HFQ7PYHNNNBCE I / InstantRun:即时运行运行时启动。 Android包是myname.company.com.soap__03,真正的应用程序类是null。 E / MultiWindowProxy:getServiceInstance失败了! D / libc-netbsd:[getaddrinfo]:hostname =“WSDL URL and Port”; servname =(NULL);式网络标识符号= 0;标记= 0 D / libc-netbsd:[getaddrinfo]:ai_addrlen = 0; ai_canonname =(NULL);填上ai_flags = 4; ai_family = 0 D / libc-netbsd:[getaddrinfo]:hostname =“WSDL URL and Port”; servname =(NULL);式网络标识符号= 0;标记= 0 D / libc-netbsd:[getaddrinfo]:ai_addrlen = 0; ai_canonname =(NULL);填上ai_flags = 4; ai_family = 0 I / HTTP客户端:HTTP状态代码:0
示例代码摘自:ВладимирЛапенков文章:How to call a SOAP web service on Android
任何人都可以告诉我哪里出错了/而是提供一个有效的例子......?
答案 0 :(得分:0)
很高兴你问这个问题,当我开始使用soap webservice时,我遇到了同样的问题。这里的关键是避免使用soap库,并使用java提供的类来发出请求并解析它,即http,DOM解析器或SAX解析器。这是您在不使用ksoap或任何其他库的情况下提出请求的方式。
现在开始使用androiod代码:
我们将创建一个名为runTask的类,它扩展异步任务并使用http发送请求主体并获取请求响应:
private class runTask extends AsyncTask<String, String, String> {
private String response;
String string = "your string parameter"
String SOAP_ACTION = "your soap action here";
String stringUrl = "http://your_url_here";
//if you experience a problem with url remove the '?wsdl' ending
@Override
protected String doInBackground(String... params) {
try {
//paste your request structure here as the String body.
String body = "<soapenv:Envelope xmlns:soapenv=\"http://someurl\" "+
"xmlns:soap=\"someurl\" "+
"xmlns:gen=\"http://someurl\"> "+
"<soapenv:Header> "+
"<auth:EventID xmlns:auth='http://someurl'>3000</auth:EventID> "+
"</soapenv:Header> "+
"<soapenv:Body> "+
"<gen:getGenericResult> "+
"<Request> "+
"<dataItem> "+
"<name>Username</name> "+
"<type>String</type> "+
"<value>usernamehere</value> "+
"</dataItem> "+
"<dataItem> "+
"<name>Password</name> "+
"<type>String</type> "+
"<value>passwordhere</value> "+
"</dataItem> "+
"</Request> "+
"</gen:getGenericResult> "+
"</soapenv:Body> "+
"</soapenv:Envelope>";
try {
URL url = new URL(stringUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDefaultUseCaches(false);
conn.setRequestProperty("Accept", "text/xml");
conn.setRequestProperty("SOAPAction", SOAP_ACTION);
//you can pass all your request parameters here usong .setRequestProperty() method
//push the request to the server address
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(body);
wr.flush();
//get the server response
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
response = builder.toString();//this is the response, parse it in onPostExecute
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
/**
* @see AsyncTask#onPostExecute(Object)
*/
@Override
protected void onPostExecute(String result) {
try {
Toast.makeText(this,"Response "+ result,Toast.LENGTH_LONG).show();
//Go ahead and parse the response now
} catch (Exception e) {
e.printStackTrace();
}
}
现在在onCreate中,继续使用以下代码执行此类
runTask task = new runTask();
task.execute();
如果网址和请求正文被正确输入,您将在onPostExecute中获得响应,格式化并从此处解析。 使用这种无库文件方式的主要优点是它非常灵活,与只使用提供的请求格式的库相比,您可以以Web服务所需的任何方式格式化请求。该解决方案可以在我的代码中无缝运行,随时可以要求进一步澄清。