Webservice呼叫一
阿新 • • 發佈:2019-01-10
程式碼準備:
1.網路上有提供一些免費的伺服器測試地址,可以上這裡找一找:https://my.oschina.net/CraneHe/blog/183471
2.我選擇了一個翻譯地址:http://www.webxml.com.cn/WebServices/TranslatorWebService.asmx
2.1開啟之後看到該地址下有一個方法:
2.2點選進入,網站會提供該方法的客戶端請求xml格式:
2.3,這個紅框部分就是我們要的,將它寫入程式碼,就可以完成請求了.
注意:以上還是獲取soap請求xml的方法,也是比較入門的方式,有經驗的筒子直接上wsdl利用解釋文件也可以自己寫xml…
然後是程式碼,我直接附上程式碼,大家直接複製即可執行,附註釋.
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 ) throwsException { //地址 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單詞的解釋,是不是簡單清楚…
第二期補充:有筒子可能有問題,那我要寫的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(); } } }
好了,將這個簡單的程式碼複製進去,替換一下請求頭和請求地址以及引數就可以得到反饋就過了,試用一下吧.