最簡單易懂的webService客戶端之soap+xml請求

代碼準備:java

  1.網絡上有提供一些免費的服務器測試地址,能夠上這裏找一找:https://my.oschina.net/CraneHe/blog/183471web

  2.我選擇了一個翻譯地址:http://www.webxml.com.cn/WebServices/TranslatorWebService.asmxapache

    2.1打開以後看到該地址下有一個方法:服務器

    2.2點擊進入,網站會提供該方法的客戶端請求xml格式:網絡

    2.3,這個紅框部分就是咱們要的,將它寫入代碼,就能夠完成請求了.app

    注意:以上仍是獲取soap請求xml的方法,也是比較入門的方式,有經驗的筒子直接上wsdl利用解釋文檔也能夠本身寫xml...post

而後是代碼,我直接附上代碼,你們直接複製便可運行,附註釋.測試

Translate.class
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 * Created by garfield on 2016/10/16.
 */



public class Translate {
    public static void translate(String word ) throws Exception {
        //地址
        String urlString = "http://www.webxml.com.cn/WebServices/TranslatorWebService.asmx ";
        //方法
        String soapActionString = "http://WebXml.com.cn/getEnCnTwoWayTranslator";
        URL url = new URL(urlString);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        //拼接請求體,此處也能夠在外面寫xml文件而後讀取,可是爲了方便一個文件搞定,並且參數也比較好傳遞咱們直接String拼接(直接將網頁上的複製進來便可)
        String soap = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                "<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/\">\n" +
                "    <soap:Body>\n" +
                "        <getEnCnTwoWayTranslator xmlns=\"http://WebXml.com.cn/\">\n" +
                "            <Word>" + word + "</Word>\n" +
                "        </getEnCnTwoWayTranslator>\n" +
                "    </soap:Body>\n" +
                "</soap:Envelope>";
        byte[] buf = soap.getBytes();
        //設置一些頭參數
        httpConn.setRequestProperty("Content-Length", String.valueOf(buf.length));
        httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
        httpConn.setRequestProperty("soapActionString", soapActionString);
        httpConn.setRequestMethod("POST");
        //輸入參數和輸出結果
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        OutputStream out = httpConn.getOutputStream();
        out.write(buf);
        out.close();

        //最後合格解析結果你們就各顯神通了,此處打印出解析的過程,最終獲得翻譯答案
        byte[] datas = readInputStream(httpConn.getInputStream());
        String result = new String(datas);
        System.out.println("result:" + result);
        System.out.println(result.substring(result.indexOf("string") - 1,result.lastIndexOf("string") + 7));
        System.out.println(result.substring(result.indexOf("string") - 1,result.lastIndexOf("string") + 7).replaceAll("</{0,1}(string)?>",""));
    }

    /**
     * 從輸入流中讀取數據
     *
     * @param inStream
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return data;
    }

    public static void main(String[] args) throws Exception {
        translate("sea");
    }
}

運行結果:網站

result:<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><getEnCnTwoWayTranslatorResponse xmlns="http://WebXml.com.cn/"><getEnCnTwoWayTranslatorResult><string>sea: [ si: ]</string><string>n. 海,海洋 |</string></getEnCnTwoWayTranslatorResult></getEnCnTwoWayTranslatorResponse></soap:Body></soap:Envelope>
<string>sea: [ si: ]</string><string>n. 海,海洋 |</string>
sea: [ si: ]n. 海,海洋 |

  第一行是直接返回的結果,下面兩行幫助理解解析,最後獲得sea單詞的解釋,是否是簡單清楚...url

  第二期補充:有筒子可能有問題,那我要寫的soap只有wsdl地址怎麼辦,並且還要求有請求頭驗證,這個我也找了以前寫的一個請求代碼,一樣很是簡單,用到的jar包只有httpclient

<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
      <dependency>
          <groupId>commons-httpclient</groupId>
          <artifactId>commons-httpclient</artifactId>
          <version>3.1</version>
      </dependency>

TestService.java

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by garfield on 2016/10/12.
 */
public class TestWebService {
    public static void main(String[] args) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        //拼接xml請求,帶有請求頭
        String params = "<id>5</id>";//隨手舉個例子,相似...
        String soapRequestData = "<soapenv:Envelope \n" +
                "\txmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" \n" +
                "\txmlns:ser=\"http://service.resource.ws.bd.newland.com/\">\n" +
                "   <soapenv:Header>\n" +
                "\t<serviceCode>serviceCode</serviceCode>\n" +
                "\t<userName>userName</userName>\n" +
                "\t<authCode>authCode</authCode>\n" +
                "   </soapenv:Header>\n" +
                "   <soapenv:Body>\n" +
                "      <ser:function>\n" +
                params +
                "      </ser:function>\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>\n";

        try {
            String method = "請求地址";//好比http://192.177.222.222:8888/services/Service_Name/Function_Name
            PostMethod postMethod = new PostMethod(method);
            byte[] b = soapRequestData.getBytes("utf-8");
            InputStream is = new ByteArrayInputStream(b, 0, b.length);
            RequestEntity re = new InputStreamRequestEntity(is, b.length, "application/soap+xml; charset=utf-8");
            postMethod.setRequestEntity(re);

            HttpClient httpClient = new HttpClient();
            int statusCode = httpClient.executeMethod(postMethod);
            //200說明正常返回數據
            if (statusCode != 200) {
                //internet error
                System.out.println(statusCode);
            }
            soapRequestData = postMethod.getResponseBodyAsString();
            System.out.println(soapRequestData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

好了,將這個簡單的代碼複製進去,替換一下請求頭和請求地址以及參數就能夠獲得反饋就過了,試用一下吧.

相關文章
相關標籤/搜索