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>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,505評論 6 533
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,556評論 3 418
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,463評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,009評論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,778評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,218評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,281評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,436評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,969評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,795評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,993評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,537評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,229評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,659評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,917評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,687評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,990評論 2 374

推薦閱讀更多精彩內容

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