啥也不說了,看代碼吧,都封裝好了
package cloud.data.service.service; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Array; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class WebService { public static void main(String[] args) throws Exception { //webservicve接口地址 String postUrl="http://www.webxml.com.cn/WebServices/TranslatorWebService.asmx"; // soapAction地址 String soapAction="http://WebXml.com.cn/getEnCnTwoWayTranslator"; //請求方式 post//get String requestMethod = "POST"; //參數組 Map<String, String> paramsMap = new HashMap<String, String>(); paramsMap.put("Word","sea"); String result = doSoapPost(postUrl,soapAction,requestMethod,paramsMap);//訪問接口 System.out.println("result: " + result); System.out.println("result2: " + result.substring(result.indexOf("string") - 1,result.lastIndexOf("string") + 7)); System.out.println("result3: " + result.substring(result.indexOf("string") - 1,result.lastIndexOf("string") + 7).replaceAll("</{0,1}(string)?>","")); } public static String doSoapPost(String postUrl,String soapAction,String requestMethod,Map<String, String> paramsMap) throws Exception { URL url = new URL(postUrl); 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"; for(String key : paramsMap.keySet()) { soap = soap + "<" + key + ">" + paramsMap.get(key) + "</" + key + ">\n"; } soap = soap + " </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", soapAction); httpConn.setRequestMethod(requestMethod); //輸入參數和輸出結果 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); return result; } /** * 從輸入流中讀取數據 * * @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; } }