zoukankan      html  css  js  c++  java
  • ksoap2连接 web service

    首先说说Ksoap2:  

      Ksoap是Enhydra.org组织的一个开源作品,他是基于Enhydra.org出品的开源通用XML解析器KXML上进行开发的,2002年推出了Ksoap1.2版本,2003年推出了Ksoap2版本,Ksoap2提供了对soap序列化更好的支持。Ksoap2是一个轻量级的J2ME平台的实现框架,提供了soap协议消息的组装,网络post,网络return,解析等功能。

    (下载地址:http://code.google.com/p/ksoap2-android/source/browse/m2-repo/com/google/code/ksoap2-android/ksoap2-android-assembly/3.4.0/ksoap2-android-assembly-3.4.0-jar-with-dependencies.jar)可以把文件名去掉选择你想要的版本。

      等下会用到的的一些常用接口。

    接口

    SoapEnvelope

        对应于SOAP规范中的SOAP Envelope,封装了head和body对象。

    SoapSerializationEnvelope

        SoapSerializationEnvelope是对SoapEnvelope的扩展,对SOAP序列化(Serialization)格式规范提供了支持,能够对简单对象自动进行序列化(simple object serialization)。

    SoapObject

        SoapObject更方便地构造SOAP调用;

    HttpTransport

        HttpTransport屏蔽了Internet访问/请求和获取服务器SOAP的细节。

     

     

    再来说说:

       XFire是新一代的Java Web服务引擎,XFire使得在JavaEE应用中发布Web服务变得轻而易举。和其他Web服务引擎相比,XFire的配置非常简单,可以非常容易地和Spring集成,它使得Java开发人员终于可以获得和.Net开发人员一样的开发效率。

       但是, 他已经被CXF 所取代了,CXF继承了 Celtix 和 XFire 两大开源项目的精华,提供了对 JAX-WS 全面的支持,并且提供了多种 Binding 、DataBinding、Transport 以及各种 Format 的支持,并且可以根据实际项目的需要,采用代码优先(Code First)或者 WSDL 优先(WSDL First)来轻松地实现 Web Services 的发布和使用。Apache CXF已经是一个正式的Apache顶级项目。

      不过这里仍然用的时Xfire

     

    好了,开始正题

      先新建一个web service project

      这里别忘了选择Xfire

     

     

      对于myeclipse没有Xfire的情况:

    进入help->MyEclipse Configer Center ,点选Software选项卡,左侧有个Browse Software,点击导航右侧的 Add Site,弹出对话框,填入名称“XFire”(任填)和站点'  http://dist.codehaus.org/xfire/update/  ', 在Browse Software下多了XFire的选项,双击选项,然后在Updates Aviables里面在单选框中打对勾,然后更新,会弹出更新向导,然后Next。。。

       然后  定义个接口

    package hpu.lyl.filestore.services;
    
    public interface IFileServices {
    //保存文件
    public void save(String fileName, String content) throws Exception; //读取文件 public String load(String fileName) throws Exception; }

       接着 实现接口

    package hpu.lyl.filestore.services.impl;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.PrintStream;
    import java.util.Scanner;
    
    import hpu.lyl.filestore.services.IFileServices;
    
    public class FileServicesImpl implements IFileServices{
        public String load(String fileName) throws Exception {
            File file = new File("D:" + File.separator + "android"
                    + File.separator + fileName);
    //判断文件是否存在
    if(!file.exists()){ return null ; } StringBuffer buf = new StringBuffer() ; Scanner scan = new Scanner(new FileInputStream(file)) ; scan.useDelimiter(" ") ; while(scan.hasNext()){ buf.append(scan.next()) ; } scan.close(); return buf.toString() ; } public void save(String fileName, String content) throws Exception { File file = new File("D:" + File.separator + "android" + File.separator + fileName); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } PrintStream out = new PrintStream(new FileOutputStream(file)); out.print(content); out.close(); } }

    然后 新建一个 web service

     下一步

     在下一步 填入你定义的接口和接口实现类 就行了

    然后在 浏览器中输入:http://192.168.156.1/FilesProject/services/lyl?wsdl   如果可以看到描述信息 ,证明后台就布置好了。

    这里在说说两句:

    1、webservice

    Web service是一个平台独立的,低耦合的,自包含的、基于可编程的web的应用程序,可使用开放的XML标准来描述、发布、发现、协调和配置这些应用程序,用于开发分布式的互操作的应用程序。

    2、wsdl

    网络服务描述语言是一个用来描述Web服务和说明如何与Web服务通信的XML(标准通用标记语言的子集)语言。为用户提供详细的接口说明书。

    3、soap

    简单对象访问协议是交换数据的一种协议规范,是一种轻量的、简单的、基于XML(标准通用标记语言下的一个子集)的协议,它被设计成在WEB上交换结构化的和固化的信息。

     

    然后就是android端了

    首先要导入 Xfire的jar包

    选择工程右键properties

    java build path

    add External Jars:

     

    然后这里要特别注意一下:选择Order and Export  将导入的包打上对勾

    不然就会这样的报错: java.lang.NoClassDefFoundError

    因为jar包没有导进apk

     

     

    package com.example.webserviceproject;
    
    import java.io.IOException;
    
    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.HttpTransportSE;
    import org.xmlpull.v1.XmlPullParserException;
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
        private Button save = null;
        private Button load = null;
        private TextView show = null;
        private static final String NAMESPACE = "http://192.168.156.1/";
        private static final String URL = "http://192.168.156.1/FilesProject/services/lyl";
        private static final String SAVE_METHOD_NAME = "save";
        private static final String LOAD_METHOD_NAME = "load";
        private static final String SOAP_ACTION = "http://192.168.156.1/FilesProject/services/";
        private Handler handle=new Handler(){
            public void handleMessage(android.os.Message msg) {
                if(msg.what==0){
                    show.setText(msg.obj.toString());
                }
                if(msg.what==1){
                    Toast.makeText(MainActivity.this, "数据保存成功", Toast.LENGTH_SHORT)
                    .show();
                }
            }; 
        };
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            this.save = (Button) super.findViewById(R.id.save);
            this.load = (Button) super.findViewById(R.id.load);
            this.show = (TextView) super.findViewById(R.id.show);
            this.save.setOnClickListener(new SaveOnClickListenerImpl());
            this.load.setOnClickListener(new LoadOnClickListenerImpl());
    
        }
    
        public class SaveOnClickListenerImpl implements OnClickListener {
            public void onClick(View v) {
                Thread thread = new Thread(null, saveInThread, "save");
                thread.start();
            }
    
        }
    
        public class LoadOnClickListenerImpl implements OnClickListener {
            public void onClick(View v) {
                Thread thread = new Thread(null, loadInThread, "load");
                thread.start();
            }
    
        }
    
        public Runnable saveInThread = new Runnable() {
            public void run() {
                
                SoapObject soapObject = new SoapObject(NAMESPACE, SAVE_METHOD_NAME);
                System.out.println("ssss");
                soapObject.addProperty("fileName", "lyl.txt");
                soapObject.addProperty("content", "ni hao wo shi ni da ye");
            
    //            常量SoapEnvelope.VER10:对应于SOAP 1.0规范
    //            常量SoapEnvelope.VER11:对应于SOAP 1.1规范 
    //            常量SoapEnvelope.VER12:对应于SOAP 1.2规范
                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                        SoapEnvelope.VER11);
                envelope.bodyOut = soapObject;
                envelope.dotNet = false;
                envelope.setOutputSoapObject(soapObject);
                // 传输
    //            HttpTransport是一个强大的辅助类,来完成Http-call
    //            它封装了网络请求的一切,你完全不用考虑序列化消息。
    //            HttpTransport仅仅负责把SoapEnvelope发送出去并接收响应
                HttpTransportSE trans = new HttpTransportSE(URL);
    //            通过设置它的debug属性为true来打开调试信息。
                trans.debug = true; // 使用调试功能
                try {
    //            可以发送请求给服务器、接收服务器响应并序列化SOAP消息
                    trans.call(SOAP_ACTION, envelope);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (XmlPullParserException e) {
                    e.printStackTrace();
                }
                Message msg=handle.obtainMessage(1);
                msg.sendToTarget();
            }
        };
    
    
        public Runnable loadInThread = new Runnable() {
            public void run() {
                SoapObject soapObject = new SoapObject(NAMESPACE, LOAD_METHOD_NAME);
                soapObject.addProperty("fileName", "lyl.txt");
                SoapSerializationEnvelope soapSerializationEnvelope = new SoapSerializationEnvelope(
                        SoapEnvelope.VER11);
                soapSerializationEnvelope.bodyOut=soapObject;
                soapSerializationEnvelope.dotNet=false;
                soapSerializationEnvelope.setOutputSoapObject(soapObject);
                HttpTransportSE trans=new HttpTransportSE(URL);
                trans.debug=true;
                try {
                    trans.call(SOAP_ACTION, soapSerializationEnvelope);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (XmlPullParserException e) {
                    e.printStackTrace();
                }
                SoapObject result=(SoapObject)soapSerializationEnvelope.bodyIn;
                Message msg=handle.obtainMessage(0, result.getProperty(0));
                msg.sendToTarget();
                System.out.println("ddddddddddddddd");
            }
        };
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            if (id == R.id.action_settings) {
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }

     

    配置权限:

     <uses-permission android:name="android.permission.INTERNET"/>

    布局自己搞定。

     

     

     

  • 相关阅读:
    sass和compass的配置
    MAC apache配置
    js库
    Tomcat7 配置 ssl
    同一对象内的嵌套方法调用AOP失效原因分析
    Spring Boot文件无法下载问题排查过程记录
    Apache、Spring、Cglib的beancopy效率对比
    使用in作为查询条件优化SQL并使用set筛选结果集
    Java使用foreach遍历集和时不能add/remove的原因剖析
    Python爬虫实践——爬取网站文章
  • 原文地址:https://www.cnblogs.com/mydomainlistentome/p/4709474.html
Copyright © 2011-2022 走看看