C/C++教程

WEB SERVICE

本文主要是介绍WEB SERVICE,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

public class Test2 {
    public static void main(String[] args) throws IOException {
        //第一步:建立服務地址
        URL url = new URL("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl");
        //第二步:開啟一個通向服務地址的連線
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //第三步:設定引數
        //3.1傳送方式設定:POST必須大寫
        connection.setRequestMethod("POST");
        //3.2設定資料格式:content-type
        connection.setRequestProperty("content-type", "text/xml;charset=utf-8");
        //3.3設定輸入輸出,因為預設新建立的connection沒有讀寫許可權,
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //第四步:組織SOAP資料,傳送請求
        String soapXML = getXML("12345");
        //將資訊以流的方式傳送出去
        OutputStream os = connection.getOutputStream();
        os.write(soapXML.getBytes());
        //第五步:接收服務端響應,列印
        int responseCode = connection.getResponseCode();
        if(200 == responseCode){//表示服務端響應成功
            //獲取當前連線請求返回的資料流
            InputStream is = connection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);

            StringBuilder sb = new StringBuilder();
            String temp = null;
            while(null != (temp = br.readLine())){
                sb.append(temp);
            }

            /**
             * 列印結果
             */
            System.out.println(sb.toString());

            is.close();
            isr.close();
            br.close();
        }
        os.close();
    }


    public static String getXML(String phone){

        String soapXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                +"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2003/XMLSchema-instance\" "
                +"xmlns:web=\"http://WebXml.com.cn/\"  "
                +"xmlns:xsd=\"http://www.w3.org/2003/XMLSchema\" "
                +"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                +"<soap:Body>"
                +"<web:getMobileCodeInfo>"
                +phone
                +"</web:getMobileCodeInfo>"
                +"</soap:Body>"
                +"</soap:Envelope>";
        return soapXML;
    }
}
这篇关于WEB SERVICE的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!