安卓中的REST和SOAP网络服务

10

我找到了使用kSOAP API使用SOAP Web服务的教程。有人能够为我提供在Android中获取REST Web服务和SOAP Web服务的示例程序(教程)吗?我已经搜索了很多,但没有找到这种类型的教程。


你能澄清一下吗?REST和SOAP都是通过Http进行RPC的方式。你需要同时使用这两种方法,并且想要关于这两种方法的教程吗? - Glenn Bech
2个回答

33

SOAP

优点:

  • 语言、平台和传输方式不受限制
  • 设计用于处理分布式计算环境
  • 是Web服务的主流标准,因此得到其他标准(WSDL、WS-*)的更好支持以及来自供应商的工具
  • 内置错误处理(故障)
  • 可扩展性

缺点:

  • 概念上更加困难、比REST更“重量级”
  • 更冗长
  • 开发更困难,需要使用工具

REST

优点:

  • 语言和平台不受限制
  • 比SOAP开发更简单
  • 学习曲线小,对工具的依赖较少
  • 简洁,不需要额外的消息层
  • 在设计和哲学上更接近Web

缺点:

  • 假定点对点通信模型--不能用于消息可能通过一个或多个中间层的分布式计算环境
  • 缺乏安全、策略、可靠消息等方面的标准支持,因此具有更复杂要求的服务更难开发(需要自己开发)
  • 与HTTP传输模型绑定

REST示例

使用Apache http jar

public void callRestWebService(){  
          System.out.println(".....REST..........");
             HttpClient httpclient = new DefaultHttpClient();  
             HttpGet request = new HttpGet(wsdlURL);  
             request.addHeader("company name", "abc");  

             request.addHeader("getAccessNumbers","http://service.xyz.com/");
             ResponseHandler<String> handler = new BasicResponseHandler();  
             try {  
                 result = httpclient.execute(request, handler); 
                 System.out.println("..result..."+result);
             } catch (ClientProtocolException e) {  
                 e.printStackTrace();  
             } catch (IOException e) {  
                 e.printStackTrace();  
             }  
             httpclient.getConnectionManager().shutdown();  

         } // end callWebService()  
     } 

SOAP示例

您可以使用ksoap,也可以自己创建SOAP XML并将其发送到URL。

private boolean callSOAPWebService() {
        OutputStream out = null;
        int respCode = -1;
        boolean isSuccess = false;
        URL url = null;
        HttpsURLConnection httpURLConnection = null;

        try {

            url = new URL(wsdlURL);


            httpURLConnection = (HttpsURLConnection) url.openConnection();

            do {
                // httpURLConnection.setHostnameVerifier(DO_NOT_VERIFY);
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection
                        .setRequestProperty("Connection", "keep-alive");
                httpURLConnection
                        .setRequestProperty("Content-Type", "text/xml");
                httpURLConnection.setRequestProperty("SendChunked", "True");
                httpURLConnection.setRequestProperty("UseCookieContainer",
                        "True");
                HttpURLConnection.setFollowRedirects(false);
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setUseCaches(true);
                httpURLConnection.setRequestProperty("Content-length",
                        getReqData().length + "");
                httpURLConnection.setReadTimeout(10 * 1000);
                // httpURLConnection.setConnectTimeout(10 * 1000);
                httpURLConnection.connect();

                out = httpURLConnection.getOutputStream();

                if (out != null) {
                    out.write(getReqData());
                    out.flush();
                }

                if (httpURLConnection != null) {
                    respCode = httpURLConnection.getResponseCode();
                    Log.e("respCode", ":" + respCode);

                }
            } while (respCode == -1);

            // If it works fine
            if (respCode == 200) {
                try {
                    InputStream responce = httpURLConnection.getInputStream();
                    String str = convertStreamToString(responce);
                    System.out.println(".....data....." + new String(str));

                    // String str
                    // =Environment.getExternalStorageDirectory().getAbsolutePath()+"/sunilwebservice.txt";
                    // File f = new File(str);
                    //
                    // try{
                    // f.createNewFile();
                    // FileOutputStream fo = new FileOutputStream(f);
                    // fo.write(b);
                    // fo.close();
                    // }catch(Exception ex){
                    // ex.printStackTrace();
                    // }
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            } else {
                isSuccess = false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out = null;
            }
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
                httpURLConnection = null;
            }
        }
        return isSuccess;
    }

    public static String createSoapHeader() {
        String soapHeader = null;

        soapHeader = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                + "<soap:Envelope "
                + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\""
                + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
                + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" + ">";
        return soapHeader;
    }

    public static byte[] getReqData() {
        StringBuilder requestData = new StringBuilder();

        requestData.append(createSoapHeader());
        requestData
                .append("<soap:Body>"
                        + "<getAccessNumbers"
                        + " xmlns=\"http://service.xyz.com.com/\""

                        + "</getAccessNumbers> </soap:Body> </soap:Envelope>");

        return requestData.toString().trim().getBytes();
    }

    private static String convertStreamToString(InputStream is)
            throws UnsupportedEncodingException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,
                "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();

    }

2

你好,这里有一个实现SOAP的好例子。

我已经使用过这个例子,并且它对我完美地起作用了。你可以从这里下载ksoap2-android-assembly-2.4-jar-with-dependencies.jar库。

这是我的代码片段....

    String NAMESPACE = "http://www.namespace.com/";
    String METHOD_NAME = "login";
    String SOAP_ACTION = "http://www.namespace.com/loginRequest";
    String URL = "http://www.domainname.com:8080/AccessWEbService?wsdl";

    SoapObject loginRequest = new SoapObject(NAMESPACE, METHOD_NAME);
    SoapObject inLoginDto = new SoapObject(NAMESPACE, "LoginDetail");

    inLoginDto.addAttribute("username", "");
    inLoginDto.addProperty("username", etUserName.getText().toString());
    inLoginDto.addProperty("password", etPassword.getText().toString());

    loginRequest.addProperty("loginDetails", inLoginDto);

    Log.e("Soap Request : ", "" + loginRequest);

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.setOutputSoapObject(loginRequest);

    AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
    try {
        androidHttpTransport.call(SOAP_ACTION, envelope);
        SoapObject response = (SoapObject) envelope.getResponse();

        Boolean loginStatus = Boolean.getBoolean(response.getProperty("success").toString());
    } 
    catch (Exception e) {
        Log.e("Exception ", "" + e);
    }

如果可以帮助你,就试一试吧...


为什么您在 inLoginDto.addAttribute("username", ""); 中设置了这个属性? - Dimitri

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接