WebService SOAP、Restful和HTTP(post/get)请求区别

web service(SOAP)

Webservice的一个最基本的目的就是提供在各个不同平台的不同应用系统的协同工作能力。 
Web service 就是一个应用程序,它向外界暴露出一个能够通过Web进行调用的API。 
SOAP是一种简单基于xml的轻量协议,用户web上交换结构化信息和类型信息。 
soap请求是HTTP POST的一个专用版本,遵循一种特殊的xml消息格式Content-type设置为: text/xml任何数据都可以xml化。 
本文将通过一个简单的示例讲解和演示Android平台的Web Service开发。

Ksoap2-android简介

  在Android平台调用Web Service需要依赖于第三方类库ksoap2,它是一个SOAP Web service客户端开发包,主要用于资源受限制的Java环境如Applets或J2ME应用程序(CLDC/ CDC/MIDP)。认真读完对ksoap2的介绍你会发现并没有提及它应用于Android平台开发,没错,在Android平台中我们并不会直接使用ksoap2,而是使用ksoap2 android。KSoap2 Android 是Android平台上一个高效、轻量级的SOAP开发包,等同于Android平台上的KSoap2的移植版本。

  需要引入ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar
//WebService的命名空间
  static final String namespace = "http://impl.service.suncreate.com";
  //服务器发布的url
  static final String url = http://10.100.3.41/axis2/services/UploadService;
  final String methodName = "upload"; // 函数名
  final int sessionID = "111111";  //sessionID
  //创建HttpTransportSE对象,通过HttpTransportSE类的构造方法可以指定WebService的url
  HttpTransportSE transport = new HttpTransportSE(url);
  transport.debug = true;
  //指定WebService的命名空间和函数名
  SoapObject soapObject = new SoapObject(namespace, methodName);
  //设置调用方法参数的值
  soapObject.addProperty("sessionID", sessionID); //sessionID
  soapObject.addProperty("data", cds); //cds是需要传递的对象
  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);
  envelope.bodyOut = transport;
  envelope.setOutputSoapObject(soapObject);
  //使用call方法调用WebService方法
  transport.call(null, envelope);
  SoapObject sb = (SoapObject) envelope.bodyIn;
  String xmlMessage = sb.toString(); // 获取从服务器端返回的XML字符串
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

Restful

REST(Representational State Transfer)一种轻量级的Web Service架构,可以完全通过HTTP协议实现。其实现和操作比SOAP和XML-RPC更为简洁,还可以利用缓存Cache来提高响应速度,性能、效率和易用性上都优于SOAP协议。 
REST架构对资源的操作包括获取、创建、修改和删除资源的操作正好对应HTTP协议提供的GET、POST、PUT和DELETE方法(Verb)

Restful与SOAP的区别

安全性:SOAP会好于restful 
效率和易用性(REST更胜一筹) 
成熟度(总的来说SOAP在成熟度上优于REST)

HTTP-GET 和 HTTP-POST 
HTTP-GET和HTTP-POST是标准协议,他们使用HTTP(超文本传输协议)谓词(谓词是指条件表达式的求值返回真或假的过程。)对参数进行编码并将参数作为名称/值对传递,还使用关联的请求语义。每个协议都包含一系列HTTP请求标头,HTTP请求标头及其他一些信息定义客户端向服务器请求哪些内容,哪个服务器用一系列HTTP响应标头和所请求的数据进行响应。

HTTP-GET 使用 MIME 类型 application/x-www-form-urlencoded(将追加到处理请求的服务器的 URL 中)以 URL 编码文本的形式传递其参数。 URL 编码是一种字符编码形式,可确保传递的参数中包含一致性文本,例如将空格编码为 %20,其它符号转换为%XX,其中XX为该符号以16进制表示的ASCII(或ISO Latin-1)值。 追加的参数也称为查询字符串。

与 HTTP-GET 类似,HTTP-POST 参数也是 URL 编码的。 但是,名称/值对是在实际的 HTTP 请求消息内部传递的,而不是作为 URL 的一部分进行传递。 
我们日常网站、系统都是使用这种形式进行访问我们的应用程序。

package cn.roco.manage.service;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class NewsService {

    public static final int POST = 1;
    public static final int GET = 2;
    public static final int HttpClientPost = 3;

    /**
     * 保存数据
     * 
     * @param title
     *            标题
     * @param length
     *            时长
     * @param flag
     *            true则使用POST请求 false使用GET请求
     * @return 是否保存成功
     * @throws Exception
     */
    public static boolean save(String path, String title, String timelength,
            int flag) throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        params.put("title", title);
        params.put("timelength", timelength);
        switch (flag) {
        case POST:
            return sendPOSTRequest(path, params, "UTF-8");
        case GET:
            return sendGETRequest(path, params, "UTF-8");
        case HttpClientPost:
            return sendHttpClientPOSTRequest(path, params, "UTF-8");
        }
        return false;
    }

    /**
     * 通过HttpClient框架发送POST请求
     * HttpClient该框架已经集成在android开发包中
     * 个人认为此框架封装了很多的工具类,性能比不上自己手写的下面两个方法
     * 但是该方法可以提高程序员的开发速度,降低开发难度
     * @param path
     *            请求路径
     * @param params
     *            请求参数
     * @param encoding
     *            编码
     * @return 请求是否成功
     * @throws Exception
     */
    private static boolean sendHttpClientPOSTRequest(String path,
            Map<String, String> params, String encoding) throws Exception {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();// 存放请求参数
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                //BasicNameValuePair实现了NameValuePair接口
                pairs.add(new BasicNameValuePair(entry.getKey(), entry
                        .getValue()));
            }
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, encoding);    //pairs:请求参数   encoding:编码方式
        HttpPost httpPost = new HttpPost(path); //path:请求路径
        httpPost.setEntity(entity); 

        DefaultHttpClient client = new DefaultHttpClient(); //相当于浏览器
        HttpResponse response = client.execute(httpPost);  //相当于执行POST请求
        //取得状态行中的状态码
        if (response.getStatusLine().getStatusCode() == 200) {
            return true;
        }
        return false;
    }

    /**
     * 发送POST请求
     * 
     * @param path
     *            请求路径
     * @param params
     *            请求参数
     * @param encoding
     *            编码
     * @return 请求是否成功
     * @throws Exception
     */
    private static boolean sendPOSTRequest(String path,
            Map<String, String> params, String encoding) throws Exception {
        StringBuilder data = new StringBuilder();
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                data.append(entry.getKey()).append("=");
                data.append(URLEncoder.encode(entry.getValue(), encoding));// 编码
                data.append('&');
            }
            data.deleteCharAt(data.length() - 1);
        }
        byte[] entity = data.toString().getBytes(); // 得到实体数据
        HttpURLConnection connection = (HttpURLConnection) new URL(path)
                .openConnection();
        connection.setConnectTimeout(5000);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length",
                String.valueOf(entity.length));

        connection.setDoOutput(true);// 允许对外输出数据
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(entity);

        if (connection.getResponseCode() == 200) {
            return true;
        }
        return false;
    }

    /**
     * 发送GET请求
     * 
     * @param path
     *            请求路径
     * @param params
     *            请求参数
     * @param encoding
     *            编码
     * @return 请求是否成功
     * @throws Exception
     */
    private static boolean sendGETRequest(String path,
            Map<String, String> params, String encoding) throws Exception {
        StringBuilder url = new StringBuilder(path);
        url.append("?");
        for (Map.Entry<String, String> entry : params.entrySet()) {
            url.append(entry.getKey()).append("=");
            url.append(URLEncoder.encode(entry.getValue(), encoding));// 编码
            url.append('&');
        }
        url.deleteCharAt(url.length() - 1);
        HttpURLConnection connection = (HttpURLConnection) new URL(
                url.toString()).openConnection();
        connection.setConnectTimeout(5000);
        connection.setRequestMethod("GET");
        if (connection.getResponseCode() == 200) {
            return true;
        }
        return false;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165

SOAP与HTTP的区别

大多数对外接口会实现web service方法而不是http方法。 c
web service相对http (post/get)的好处

1.接口中实现的方法和要求参数一目了然

2.不用担心大小写问题

3.不用担心中文urlencode问题

4.代码中不用多次声明认证(账号,密码)参数

5.传递参数可以为数组,对象等…

6.web service相对http(post/get)由于要进行xml解析,速度可能会有所降低。

7.web service 完全可以可以被http(post/get)替代,而且现在的开放平台都是用的HTTP(post/get)实现的。