如何调用SOAP Web服务使用简单的字符串(XML字符串格式) [英] How to call a SOAP webservice with a simple String (xml in string format)

查看:530
本文介绍了如何调用SOAP Web服务使用简单的字符串(XML字符串格式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个字符串重新presenting一个XML:

 字符串的SOAPCall =<肥皂:信封XMLNS:肥皂=http://www.w3.org/2001/12/soap-envelopeSOAP:encodingStyle的=HTTP ://www.w3.org/2001/12/soap-encoding><肥皂:身体的xmlns:M =http://www.example.org/stock>< M:addDownloadParams>&LT ;米:idApp>中;
的SOAPCall + = idApp;
的SOAPCall + =< M:versionApp&​​gt;中;
的SOAPCall + = versonApp;
的SOAPCall + =< / M:versionApp&​​GT;< M:OS>的Andr​​oid< / M:OS>< / M:addDownloadParams>< / SOAP:身体与GT;< /肥皂:信封>中;
 

和我有这个肥皂Web服务:

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

现在,我需要将字符串传递到Android肥皂web服务,但我不认识路,我知道我需要使用httpcliente:

  HttpClient的HttpClient的=新DefaultHttpClient();
HttpContext的localContext =新BasicHttpContext();
 

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

任何一个富人code的例子吗?我无法找到它的谷歌。我不想使用图书馆,我需要我自己做的。

感谢

编辑:这是code现在,但它不工作,我得到错误500内部服务器错误:

 公共静态的byte [] addDownloadIntoServer(){
        byte []的结果= NULL;

        字符串SERVER_URL =htt​​p://stats.mywebsite.com/ws/server.php;
        字符串SOAP_ACTION =addDownload;
        ?< XML版本= \字符串的身体= 1.0 \编码= \UTF-8 \>< SOAP-ENV:信封的xmlns:SOAP-ENV = \HTTP://schemas.xmlsoap。组织/ SOAP /信封/ \的xmlns:NS1 = \HTTP://stats.mobincube.com/ \>< SOAP-ENV:身体与GT;< NS1:addDownloadParams>中;
    机身+ =< idApp>中+ SectionManager.instance.app_id +&所述; / idApp>中;
    机身+ =< versionApp&​​GT;+ SectionManager.instance.app_version +< / versionApp&​​gt;中;
    机身+ =<信源>的android< /源>< OS>的Andr​​oid< / OS>< / NS1:addDownloadParams>< / SOAP-ENV:身体与GT;< / SOAP-ENV:信封>中;

        的HttpParams httpParameters =新BasicHttpParams();
        //毫秒设置超时,直到建立了连接。
        INT timeoutConnection = 15000;
        HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection);
        //设置默认套接字超时(SO_TIMEOUT)
        //毫秒这是超时等待数据。
        INT timeoutSocket = 35000;
        HttpConnectionParams.setSoTimeout(httpParameters,timeoutSocket);

        DefaultHttpClient的HttpClient =新DefaultHttpClient(httpParameters);

        / *
        * httpclient.getCredentialsProvider()。setCredentials方法(新
        * AuthScope(os.icloud.com,80,NULL,文摘),新
        * UsernamePasswordCredentials(用户名,密码));
        * /
        HttpPost httppost =新HttpPost(SERVER_URL);
        httppost.setHeader(SOAPAction报,SOAP_ACTION);
        httppost.setHeader(内容类型,为text / xml;字符集= UTF-8);

        的System.out.println(执行请求+ httppost.getRequestLine());
        //现在如下创建SOAP请求消息:
        最后的StringBuffer肥皂=新的StringBuffer();
        soap.append(\ N);
        soap.append();
        //这是一个示例data..you必须创建自己需要的数据BEGIN
        soap.append(\ N);
        soap.append(\ N);
        soap.append(+体);
        soap.append(\ N);
        soap.append(\ N);

        / * soap.append(体); * /
        // END邮件正文
        soap.append();
        Log.i(SOAP请求,+ soap.toString());
        //全SOAP请求消息END
        尝试 {
            HttpEntity实体=新StringEntity(soap.toString(),HTTP.UTF_8);
            httppost.setEntity(实体);
            HTT presponse响应= httpclient.execute(httppost); //调用服务器
            HttpEntity r_entity = response.getEntity(); //得到响应
            Log.i(效应初探头,开始......); //响应头
            Log.i(效应初探头,状态行:+ response.getStatusLine());
            标题[]头= response.getAllHeaders();
            对于(标题H:头)
                Log.i(效应初探头,h.getName()+:+ h.getValue());

            Log.i(效应初探头,END ......);
            如果(r_entity!= NULL){
                结果=新的字节[(INT)r_entity.getContentLength()];
                如果(r_entity.isStreaming()){
                    的DataInputStream是=新的DataInputStream(
                    r_entity.getContent());
                    is.readFully(结果);
                }
            }
        }赶上(例外五){
            Log.i(异常而连接,+ E.getMessage());
            E.printStackTrace();
        }

        。httpclient.getConnectionManager()关闭(); //关闭连接
        返回结果;
    }
 

解决方案

解决方法:

 专用字节[] callSOAPServer(){

    byte []的结果= NULL;

    的HttpParams httpParameters =新BasicHttpParams();
    //毫秒设置超时,直到建立了连接。
    INT timeoutConnection = 15000;
    HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection);
    //设置默认套接字超时(SO_TIMEOUT)
    //毫秒这是超时等待数据。
    INT timeoutSocket = 35000;
    HttpConnectionParams.setSoTimeout(httpParameters,timeoutSocket);

    DefaultHttpClient的HttpClient =新DefaultHttpClient(httpParameters);

    / *
     * httpclient.getCredentialsProvider()。setCredentials方法(新
     * AuthScope(os.icloud.com,80,NULL,文摘),新
     * UsernamePasswordCredentials(用户名,密码));
     * /
    HttpPost httppost =新HttpPost(SERVER_URL);
    httppost.setHeader(SOAPAction报,SOAP_ACTION);
    httppost.setHeader(内容类型,为text / xml;字符集= UTF-8);

    的System.out.println(执行请求+ httppost.getRequestLine());
   //现在如下创建SOAP请求消息:
    最后的StringBuffer肥皂=新的StringBuffer();
    soap.append(\ N);
    soap.append();
   //这是一个示例data..you必须创建自己需要的数据BEGIN
    soap.append(\ N);
    soap.append(\ N);
    soap.append(+体);
    soap.append(\ N);
    soap.append(\ N);

    / * soap.append(体); * /
     // END邮件正文
    soap.append();
    Log.i(SOAP请求,+ soap.toString());
   //全SOAP请求消息END
    尝试 {
        HttpEntity实体=新StringEntity(soap.toString(),HTTP.UTF_8);
        httppost.setEntity(实体);
        HTT presponse响应= httpclient.execute(httppost); //调用服务器
        HttpEntity r_entity = response.getEntity(); //得到响应
        Log.i(效应初探头,开始......); //响应头
        Log.i(效应初探头,状态行:+ response.getStatusLine());
        标题[]头= response.getAllHeaders();
        对于(标题H:头){
            Log.i(效应初探头,h.getName()+:+ h.getValue());
        }
        Log.i(效应初探头,END ......);
        如果(r_entity!= NULL){
            结果=新的字节[(INT)r_entity.getContentLength()];
            如果(r_entity.isStreaming()){
                的DataInputStream是=新的DataInputStream(
                        r_entity.getContent());
                is.readFully(结果);
            }
        }
    }赶上(例外五){
        Log.i(异常而连接,+ E.getMessage());
        E.printStackTrace();
    }

    。httpclient.getConnectionManager()关闭(); //关闭连接
    返回结果;
   }
 

2)你必须分析上述功能的输出返回的字节数组。例如:

 字节[] initReqrepsonse = callSOAPServer(soapBodymessage);
ByteArrayInputStream的BAIS =新ByteArrayInputStream的(initReqrepsonse);
//现在解析xml作为
/ **处理XML * /
的SAXParserFactory SPF = SAXParserFactory.newInstance();
的SAXParser藻= spf.newSAXParser();
XMLReader的XR = sp.getXMLReader();

/ **创建处理程序来处理XML标签(扩展了DefaultHandler)* /
// ResponseParser是将解析XML输出​​XML解析器类。
ResponseParser myXMLHandler =新ResponseParser();
xr.setContentHandler(myXMLHandler);
Log.i(XML数据,bais.toString());
xr.parse(新的InputSource(BAIS));
 

这样,您就可以访问任何人未经第三方库SOAP Web服务的方法。 请让我知道如果任何更正要求。

I have this string representing a 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>";

And i have this soap webservice:

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

Now, i need to pass that string to that soap webservice on android, but i dont know the way, i know i need to use httpcliente:

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

but i dont know how to call the soapwebservice with that string.

Anyone haves a code example? i can't find it on google. I dont want to use a library, i need to do it by myself

Thanks

EDIT: this is the code now, but it is not working, i get error 500 internal server error:

    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;
    }

解决方案

Solution:

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) You have to parse the output of above function returned byteArray. For example:

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));

This way,you can access Any SOAP webservice methods without third-party libraries. Please let me know if any corrections are required.

这篇关于如何调用SOAP Web服务使用简单的字符串(XML字符串格式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆