Android下对接Java写的WebServer接口的实现

来源:互联网 发布:apache common实现orm 编辑:程序博客网 时间:2024/06/02 05:32

吗买比。。。。。。

在这记录一个天大的坑。。。。。这个坑掉进去好几天!!


Android下对接WebServer,啥??WebServer?我的第一反应是这货用C#写的,因为我之前有写过。。所以开始在网上找方法,。。。中间搞了几天,发觉对方一直说收不到我传过去的值,简直是超(ri)感(le)动(gou)。也中间写了.net的接口访问,访问并没什么问题,中间找了很多种方法。在网上找到了一个东西axis2。。。的因为安卓下并不能用axis2(这货依赖的rmi等包在安卓下无法使用),最终在eclipse下用axis2去写才能正常访问,通过抓包拿到了真正的访问数据。


下面把关键技术记录如下,记录这个踩过的坑,也能帮助需要的人...


Android下请求JAVA写的WebServer接口方法

仿照访问对接.net接口的形式,只是封装成的东西不一样(其实就是这么简单),用java普通的网络访问即可完成,完整代码如下。

/**     * 对接Java写的WebServer,封装成的数据格式如下     *      * <?xml version='1.0' encoding='UTF-8'?>     * <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">     * <soapenv:Body>     * <{methodName} xmlns="{namespace}">     * <arg0 xmlns="">xxx</arg0>     * <arg1 xmlns="">xxx</arg1>     * <arg2 xmlns="">xxx</arg2>     * </{methodName}>     * </soapenv:Body>     * </soapenv:Envelope>     *      *     * @param params     * @param _url     * @param namespace     * @param methodName     * @return     */    public static String doRequest2(Map<String, String> params, String _url, String namespace, String methodName) {        String str = "";        try {            URL url = new URL(_url);            HttpURLConnection con = (HttpURLConnection) url.openConnection();            con.setDoOutput(true);            con.setDoInput(true);            con.setRequestProperty("User-Agent", "Axis2");            con.setRequestProperty("SOAPAction", "");            con.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");            con.connect();            OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());            String xmlInfo = "<?xml version=\'1.0\' encoding=\'UTF-8\'?><soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"                    + "<soapenv:Body><" + methodName + " xmlns=\"" + namespace + "\">";            StringBuffer buffer = new StringBuffer();            for (Map.Entry<String, String> entry : params.entrySet()) {                buffer.append("<" + entry.getKey() + " xmlns=\"\">" + entry.getValue() + "</" + entry.getKey() + ">");            }            xmlInfo += buffer.toString() + "</" + methodName + "></soapenv:Body></soapenv:Envelope>";            out.write(new String(xmlInfo.getBytes("UTF-8")));            out.flush();            out.close();            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));            String lines;            while ((lines = reader.readLine()) != null) {                str += lines;            }            reader.close();            con.disconnect();        } catch (Exception e) {            e.printStackTrace();        }        return str;    }
这就是对接java写的WebServer接口的方法,最终出去的数据形式如下(说明:key->arg0,arg1...不管后台字段名是什么这里必须是这种key,要对应后台接口定义的参数顺序,不然接收的时候就不对应了),跟用c#下的soap协议组完的数据并不一样。

<?xml version='1.0' encoding='UTF-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">    <soapenv:Body>        <sendXXX xmlns="http://webservices.xxx.xxx.org/">            <arg0 xmlns="">2000-02-02</arg0>            <arg1 xmlns="">aaaaaaabbbbbbb</arg1>            <arg2 xmlns="">2</arg2>            <arg3 xmlns="">1</arg3>            <arg4 xmlns="">85</arg4>    <!-- 。。。 -->        </sendXXX>    </soapenv:Body></soapenv:Envelope>
请求头长这样



纯JAVA形式访问JAVA写的WebServer

其实因为我对接的接口对方是用的rmi写的,需要用java的axis2。这货需要用到一堆的jar包:axis2.rar


实现方式如下,其实上也是非常的简单,但是这个方法在安卓下没法用:

public static void test(Map<String, String> params, String _url,String namespace, String methodName) {try {Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();Object[] requestParam = new Object[19];int i = 0;while (iterator.hasNext()) {Map.Entry<String, String> next = iterator.next();requestParam[i] = new String(next.getValue().getBytes("UTF-8"));i++;}RPCServiceClient serviceClient = new RPCServiceClient();// 指定调用WebService的URLEndpointReference targetEPR = new EndpointReference(_url);Options options = serviceClient.getOptions();options.setTo(targetEPR);options.setProperty(HTTPConstants.CHUNKED, false);// 指定方法返回值的数据类型的Class对象Class[] responseParam = new Class[] { String.class };// 指定要调用的getGreeting方法及WSDL文件的命名空间QName requestMethod = new QName(namespace, methodName);// 调用方法并输出该方法的返回值String result = (String) serviceClient.invokeBlocking(requestMethod, requestParam, responseParam)[0];System.out.println(result); // 返回的xml} catch (Exception e) {e.printStackTrace();}}


-----------------------------------------------------------------分割线---------------------------------------------------------------------


附:对接.net写的WebServer接口

.net写的接口对接起来就好多了,网上有方法,在这还是记录一下:

1.方法1,用的ksoap2框架,需要用到的jar包:ksoap2-android-assembly-3.5.0-jar-with-dependencies.jar

实现方式:

/**     * 对接用.net写的WebServer     *     * @param context     * @param _params     */    public void test(Context context, Map<String, String> _params) {        String WSDL_URI = "xxxx";//wsdl 的uri        String namespace = "xxxxxx";//namespace        String methodName = "xxxxx";//要调用的方法名称        SoapObject request = new SoapObject(namespace, methodName);        request.addProperty("xxx1", "xxxx1");        request.addProperty("xxx2", "xxxx2");        request.addProperty("xxx3", "xxxx3");        //。。。        //创建SoapSerializationEnvelope 对象,同时指定soap版本号(之前在wsdl中看到的)        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11);        envelope.bodyOut = request;//由于是发送请求,所以是设置bodyOut        envelope.dotNet = true;//由于是.net开发的webservice,所以这里要设置为true        HttpTransportSE httpTransportSE = new HttpTransportSE(WSDL_URI);        try {            httpTransportSE.call(null, envelope);//调用        } catch (IOException e) {            e.printStackTrace();        } catch (XmlPullParserException e) {            e.printStackTrace();        }        // 获取返回的数据        try {            SoapObject object = (SoapObject) envelope.bodyIn;            // 获取返回的结果            if (null != object) {                Object result = object.getProperty(0);                Log.e("QL", result.toString());            }        } catch (Exception e) {            e.printStackTrace();        }    }

2.方法2,用普通的java访问类,拼接数据的形式。标签头和值需要对应不一样的WebServer接口版本和soap版本做改动。以下代码是EVR11版本的写法,如果是EVR12版本标签头是<soap12:xxx>。xmls的值对应下图来改:



/**     * 对接.net写的WebServer,与用java写的会不一样     *     * @param params     * @param _url     * @param namespace     * @param methodName     * @return     */    public static String doRequest(Map<String, String> params, String _url, String namespace, String methodName) {        try {            URL url = new URL(_url);            HttpURLConnection con = (HttpURLConnection) url.openConnection();            con.setDoOutput(true);            con.setDoInput(true);            con.setRequestMethod("POST");            con.setRequestProperty("Content-Type", "text/xml; charset=utf-8");            con.setRequestProperty("SOAPAction", "\"" + namespace + methodName + "\"");            con.connect();            OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());            String xmlInfo = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http:" +                    "//www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"                    + "<soap:Body><" + methodName + " xmlns=\"" + namespace + "\">";            StringBuffer buffer = new StringBuffer();            for (Map.Entry<String, String> entry : params.entrySet()) {                buffer.append("<" + entry.getKey() + ">" + entry.getValue() + "</" + entry.getKey() + ">");            }            xmlInfo += buffer.toString() + "</" + methodName + "></soap:Body></soap:Envelope>";            out.write(new String(xmlInfo.getBytes("UTF-8")));            out.flush();            out.close();            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));            String lines;            while ((lines = reader.readLine()) != null) {                Log.e("QL", lines);            }            reader.close();            con.disconnect();        } catch (Exception e) {            e.printStackTrace();        }        return "";    }


原创粉丝点击