WebService學習筆記(一)

一、基礎進階

  1. httpclient調用WebService
package com.demo;

import com.midea.gls.MobileCodeWS;
import com.midea.gls.MobileCodeWSSoap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * \* Created with IntelliJ IDEA.
 * \* Author: huyi
 * \* Date: 2017/2/17 22:15
 * \* Description:
 * \
 */
public class WSHttpClient {



    public static void main(String[] args) {
        String mobileCode = "18680586568";

       // get(mobileCode);
//        post(mobileCode);

        soap(mobileCode);
    }

    public static void get(String mobileCode){
        HttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("http://ws.webxml.com.cn//WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode="+mobileCode+"&userID=");
        try {
            HttpResponse response = client.execute(httpGet);
            System.out.println("executing request " + httpGet.getURI());
            // 獲取響應實體
            HttpEntity entity = response.getEntity();
            System.out.println("--------------------------------------");
            // 打印響應狀態
            System.out.println(response.getStatusLine());
            if (entity != null) {
                // 打印響應內容長度
                System.out.println("Response content length: " + entity.getContentLength());
                // 打印響應內容
                System.out.println("Response content: " + EntityUtils.toString(entity));
            }
            System.out.println("------------------------------------");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void post(String mobileCodeVal){
        HttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://ws.webxml.com.cn//WebServices/MobileCodeWS.asmx/getMobileCodeInfo");
        try {
            //設置參數
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            list.add(new BasicNameValuePair("mobileCode",mobileCodeVal));
            list.add(new BasicNameValuePair("userID",""));
            UrlEncodedFormEntity requestEntiry = new UrlEncodedFormEntity(list);
            httpPost.setEntity(requestEntiry);
            HttpResponse response = client.execute(httpPost);
            System.out.println("executing request " + httpPost.getURI());
            // 獲取響應實體
            HttpEntity httpEntity = response.getEntity();
            System.out.println("--------------------------------------");
            // 打印響應狀態
            System.out.println(response.getStatusLine());
            if (httpEntity != null) {
                // 打印響應內容長度
                System.out.println("Response content length: " + httpEntity.getContentLength());
                // 打印響應內容
                System.out.println("Response content: " + EntityUtils.toString(httpEntity));
            }
            System.out.println("------------------------------------");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void soap(String mobileVal){
        MobileCodeWS mobileCodeWS = new MobileCodeWS();
        MobileCodeWSSoap mobileCodeWSSoap = mobileCodeWS.getMobileCodeWSSoap();
        String address = mobileCodeWSSoap.getMobileCodeInfo(mobileVal, null);
        System.out.println(address);
    }
}
  1. wsimport調用WSDL
wsimport -s . -p com.midea.gls http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?WSDL

找到WSDL中關于service的調用

    public static void soap(String mobileVal){
        MobileCodeWS mobileCodeWS = new MobileCodeWS();
        MobileCodeWSSoap mobileCodeWSSoap = mobileCodeWS.getMobileCodeWSSoap();
        String address = mobileCodeWSSoap.getMobileCodeInfo(mobileVal, null);
        System.out.println(address);
    }

二 、 發布自己的WSDL

發布自己的WSDL時候,需要注意,地址欄后面要自己加?WSDL

package com.demo;

import javax.jws.WebService;
import javax.xml.ws.Endpoint;

/**
 * \* Created with IntelliJ IDEA.
 * \* Author: huyi
 * \* Date: 2017/2/20 13:32
 * \* Description:
 * \
 */
@WebService
public class MyWS {

    public String sayHello(String name) {
        String reVal = name + ", 你好!";
        System.out.println(reVal);
        return reVal;
    }

    public static void main(String[] args) {
        String address = "http://10.74.96.29/ws";
        Endpoint.publish(address , new MyWS());
        System.out.println("發布的地址是:"+address);
    }
}

訪問http://10.74.96.29/ws?WSDL,可以見到

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<wsdl:definitions xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="http://demo.com/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:ns1="http://schemas.xmlsoap.org/soap/http" name="MyWSService" targetNamespace="http://demo.com/">
<wsdl:types>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://demo.com/" elementFormDefault="unqualified" targetNamespace="http://demo.com/" version="1.0">
<xs:element name="sayHello" type="tns:sayHello"/>
<xs:element name="sayHelloResponse" type="tns:sayHelloResponse"/>
<xs:complexType name="sayHello">
<xs:sequence>
<xs:element minOccurs="0" name="arg0" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="sayHelloResponse">
<xs:sequence>
<xs:element minOccurs="0" name="return" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
</wsdl:types>
<wsdl:message name="sayHello">
<wsdl:part element="tns:sayHello" name="parameters"></wsdl:part>
</wsdl:message>
<wsdl:message name="sayHelloResponse">
<wsdl:part element="tns:sayHelloResponse" name="parameters"></wsdl:part>
</wsdl:message>
<wsdl:portType name="MyWS">
<wsdl:operation name="sayHello">
<wsdl:input message="tns:sayHello" name="sayHello"></wsdl:input>
<wsdl:output message="tns:sayHelloResponse" name="sayHelloResponse"></wsdl:output>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="MyWSServiceSoapBinding" type="tns:MyWS">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="sayHello">
<soap:operation soapAction="" style="document"/>
<wsdl:input name="sayHello">
<soap:body use="literal"/>
</wsdl:input>
<wsdl:output name="sayHelloResponse">
<soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="MyWSService">
<wsdl:port binding="tns:MyWSServiceSoapBinding" name="MyWSPort">
<soap:address location="http://10.74.96.29/ws"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>

三 、客戶端訪問

  1. 首先在CMD中調用wsimport工具生成本地WebService代碼
wsimport -s . -p com.ws http://10.74.96.29/ws?WSDL
  1. 導入代碼到本地項目后,直接調用即可
    public static void soap2(String mobileVal){
        MyWS mobileCodeWS = new MyWS();
        String name = "huyi";
        String reVal = mobileCodeWS.sayHello(name);
        System.out.println(reVal);
    }

注意:一個端口可以發布多個Webservice服務

四 、ajax訪問WebService

ajax不能直接訪問WebService,因為存在跨域的問題,需要變通一下,通過ajax調用工程下的客戶端訪問WebService,客戶端可以是一個servlet,或者spring下的controller

ws.jsp

<%--
  Created by IntelliJ IDEA.
  User: huyi
  Date: 2017/2/20
  Time: 15:05
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>

    <title>$Title$</title>
    <script src="js/jquery/jquery.min.js"></script>
    <script>


        $("#myWs").click(function () {
            console.info(data);
            /**/
            console.info("----2-------");
        })

        function getVal() {
            console.info("-----1---" + $("#myWs").val() + "------");
            var data = {
                name:$("#name").val()
            }

            $.ajax({
                method:'POST',
                url:'http://localhost:8080/ws/myWsServlet?name='+$("#name").val(),
                success:function(result) {
                    console.info("-----3---" + result + "------");
                }
            });
        }

    </script>
</head>
<body>
<input type="text" id="name">
<input type="button" name="調用WebService" id="myWs" value="調用WebService" onclick="getVal()">
</body>
</html>

servlet

package com.gls.ws;

import com.demo.*;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * \* Created with IntelliJ IDEA.
 * \* Author: huyi
 * \* Date: 2017/2/20 15:50
 * \* Description:
 * \
 */
public class MyWsServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        com.demo.MyWS mobileCodeWS = new com.demo.MyWS();
        String name = req.getParameter("name");
        String reVal = mobileCodeWS.sayHello(name);
        System.out.println(reVal+"------------");
        resp.getWriter().print(reVal);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

web.xml

    <servlet>
        <servlet-name>myWs</servlet-name>
        <servlet-class>com.gls.ws.MyWsServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>myWs</servlet-name>
        <url-pattern>/myWsServlet</url-pattern>
    </servlet-mapping>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,767評論 18 399
  • 一、Java基礎 1.寫出下面代碼的執行結果 2.寫出下面代碼的執行結果 3.寫出下面代碼的執行結果 (此題需寫出...
    joshul閱讀 543評論 0 1
  • 一. Java基礎部分.................................................
    wy_sure閱讀 3,837評論 0 11
  • 前不久,一位朋友在閑聊中提到自己孩子正在某知名英語培訓機構學習英語,目前學習自然拼讀已經一個多月,孩子在家時不時會...
    正好學拼讀閱讀 725評論 0 7
  • 文/添一抹嵐 蘆葦,是我的同桌,在四年級時。 那時,周圍同學名字里,或梅、蘭,或紅、花。當聽得蘆葦這名字時,我便先...
    添一抹嵐閱讀 988評論 58 33