java - 如何使用简单的字符串调用 SOAP 网络服务(字符串格式的 xml)

标签 java android web-services soap httpclient

我有这个代表 XML 的字符串:

String soapCall="<soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <soap:Body xmlns:m="http://www.example.org/stock"> <m:addDownloadParams> <m:idApp>";
soapCall+=idApp;
soapCall+="<m:versionApp>";
soapCall+=versonApp;
soapCall+="</m:versionApp> <m:os>Android</m:os> </m:addDownloadParams> </soap:Body> </soap:Envelope>";

我有这个 SOAP 网络服务:

http://stats.mywebsite.com/ws/adddownload

现在,我需要将该字符串传递给 android 上的那个 soap 网络服务,但我不知道方法,我知道我需要使用 httpcliente:

HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();

但我不知道如何使用该字符串调用 soapwebservice。

谁有代码示例?我无法在谷歌上找到它。我不想使用图书馆,我需要自己做

谢谢

编辑:这是现在的代码,但它不起作用,我收到错误 500 内部服务器错误:

    public static byte[] addDownloadIntoServer(){
        byte[] result = null;

        String SERVER_URL="http://stats.mywebsite.com/ws/server.php";
        String SOAP_ACTION="addDownload";
        String body="<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://stats.mobincube.com/\"><SOAP-ENV:Body><ns1:addDownloadParams>";
    body+="<idApp>" +SectionManager.instance.app_id+"</idApp>";
    body+="<versionApp>"+SectionManager.instance.app_version+"</versionApp>";
    body+="<source>android</source> <os>Android</os> </ns1:addDownloadParams></SOAP-ENV:Body></SOAP-ENV:Envelope>";

        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        int timeoutConnection = 15000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 35000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);

        /*
        * httpclient.getCredentialsProvider().setCredentials( new
        * AuthScope("os.icloud.com", 80, null, "Digest"), new
        * UsernamePasswordCredentials(username, password));
        */
        HttpPost httppost = new HttpPost(SERVER_URL );
        httppost.setHeader("soapaction", SOAP_ACTION);
        httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

        System.out.println("executing request" + httppost.getRequestLine());
        //now create a soap request message as follows:
        final StringBuffer soap = new StringBuffer();
        soap.append("\n");
        soap.append("");
        // this is a sample data..you have create your own required data  BEGIN
        soap.append(" \n");
        soap.append(" \n");
        soap.append("" + body);
        soap.append(" \n");
        soap.append(" \n");

        /* soap.append(body); */
        // END of MEssage Body
        soap.append("");
        Log.i("SOAP Request", ""+soap.toString());
        // END of full SOAP request  message
        try {
            HttpEntity entity = new StringEntity(soap.toString(),HTTP.UTF_8);
            httppost.setEntity(entity); 
            HttpResponse response = httpclient.execute(httppost);// calling server
            HttpEntity r_entity = response.getEntity();  //get response
            Log.i("Reponse Header", "Begin...");          // response headers
            Log.i("Reponse Header", "StatusLine:"+response.getStatusLine());
            Header[] headers = response.getAllHeaders();
            for(Header h:headers)
                Log.i("Reponse Header",h.getName() + ": " + h.getValue());

            Log.i("Reponse Header", "END...");
            if (r_entity != null) {       
                result = new byte[(int) r_entity.getContentLength()];  
                if (r_entity.isStreaming()) {
                    DataInputStream is = new DataInputStream(
                    r_entity.getContent());
                    is.readFully(result);
                }
            }
        }catch (Exception E) {
            Log.i("Exception While Connecting", ""+E.getMessage());
            E.printStackTrace();
        }

        httpclient.getConnectionManager().shutdown(); //shut down the connection
        return result;
    }

最佳答案

解决方案:

private byte[] callSOAPServer() {

    byte[] result = null;

    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    int timeoutConnection = 15000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 35000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);

    /*
     * httpclient.getCredentialsProvider().setCredentials( new
     * AuthScope("os.icloud.com", 80, null, "Digest"), new
     * UsernamePasswordCredentials(username, password));
     */
    HttpPost httppost = new HttpPost(SERVER_URL );
    httppost.setHeader("soapaction", SOAP_ACTION);
    httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

    System.out.println("executing request" + httppost.getRequestLine());
   //now create a soap request message as follows:
    final StringBuffer soap = new StringBuffer();
    soap.append("\n");
    soap.append("");
   // this is a sample data..you have create your own required data  BEGIN
    soap.append(" \n");
    soap.append(" \n");
    soap.append("" + body);
    soap.append(" \n");
    soap.append(" \n");

    /* soap.append(body); */
     // END of MEssage Body
    soap.append("");
    Log.i("SOAP Request", ""+soap.toString());
   // END of full SOAP request  message
    try {
        HttpEntity entity = new StringEntity(soap.toString(),HTTP.UTF_8);
        httppost.setEntity(entity); 
        HttpResponse response = httpclient.execute(httppost);// calling server
        HttpEntity r_entity = response.getEntity();  //get response
        Log.i("Reponse Header", "Begin...");          // response headers
        Log.i("Reponse Header", "StatusLine:"+response.getStatusLine());
        Header[] headers = response.getAllHeaders();
        for(Header h:headers){
            Log.i("Reponse Header",h.getName() + ": " + h.getValue());
        }
        Log.i("Reponse Header", "END...");
        if (r_entity != null) {       
            result = new byte[(int) r_entity.getContentLength()];  
            if (r_entity.isStreaming()) {
                DataInputStream is = new DataInputStream(
                        r_entity.getContent());
                is.readFully(result);
            }
        }
    } catch (Exception E) {
        Log.i("Exception While Connecting", ""+E.getMessage());
        E.printStackTrace();
    }

    httpclient.getConnectionManager().shutdown(); //shut down the connection
    return result;
   }

2) 您必须解析上述函数返回的 byteArray 的输出。例如:

byte[] initReqrepsonse = callSOAPServer(soapBodymessage );
ByteArrayInputStream bais=new ByteArrayInputStream(initReqrepsonse);
// now parse the xml as
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();

/** Create handler to handle XML Tags ( extends DefaultHandler ) */
// ResponseParser  is XML parser class which will parse the XML output.
ResponseParser myXMLHandler = new ResponseParser();
xr.setContentHandler(myXMLHandler);
Log.i("XML data", bais.toString());
xr.parse(new InputSource(bais));

这样,您就可以在没有第三方库的情况下访问任何 SOAP 网络服务方法。 如果需要任何更正,请告诉我。

关于java - 如何使用简单的字符串调用 SOAP 网络服务(字符串格式的 xml),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12561503/

相关文章:

java - 非法监控状态异常

java - 替换 fragment 时出现 NullpointerException

Android ant构建项目失败

c# - 使用 Web 服务/WCF 的命名约定且无重载

java - Android SDK Extras/目录丢失

java - 将 pcm 数据转换为低尺寸音频类型 - Java/Android

java - 将 Eclipse 连接到 mysql mac os x jdbc 驱动程序

Android从按钮打开相机

php - 如何为 php-database-webservice 授权 android 应用程序?

android - 哪个网络平台最适合使用 Android 客户端创建网络应用程序