1. 程式人生 > >總結幾種訪問webservice介面的方式

總結幾種訪問webservice介面的方式

使用axis2

public static final String URL = "http://fy.webxml.com.cn/webservices/EnglishChinese.asmx";
	public String englishToChinese(String word) {
		try {
			EnglishChineseStub stub = new EnglishChineseStub(URL);
			EnglishChineseStub.TranslatorString translator = new EnglishChineseStub.TranslatorString
(); translator.setWordKey(word); TranslatorStringResponse translatorString = stub.translatorString(translator); ArrayOfString stringResult = translatorString.getTranslatorStringResult(); String[] strings = stringResult.getString(); Arrays.asList(strings).forEach(t->System.out.println
(t)); } catch (AxisFault e) { e.printStackTrace(); }catch(Exception e) { e.printStackTrace(); } return null; }

使用httpclient

  • 引入jar檔案
    開發客戶單程式碼
public class HttpclientForWebService {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpclientForWebService.class);
    private
static final String UTF_8 = "utf-8"; private static final String CONTENT_TYPE = "text/xml; charset=utf-8"; public static final String SUCCESS = "success"; public static final String MSG = "msg"; public static final String RESULTCODE = "resultCode"; private String methodName; private String wsdlLocation; public HttpclientForWebService() { super(); } public HttpclientForWebService(String wsdlLocation) { this.wsdlLocation = wsdlLocation; } public HttpclientForWebService(String methodName, String wsdlLocation) { this.methodName = methodName; this.wsdlLocation = wsdlLocation; } // 執行請求方法 public Map<String, Object> invoke(Map<String, String> patameterMap) { PostMethod postMethod = new PostMethod(wsdlLocation); String soapRequestData = buildRequestData(patameterMap); LOGGER.info("請求報文資料:wsdlLocation:{},data:{}", wsdlLocation, soapRequestData); Map<String, Object> result = new HashMap<>(); try { byte[] bytes = soapRequestData.getBytes(UTF_8); InputStream inputStream = new ByteArrayInputStream(bytes, 0, bytes.length); RequestEntity requestEntity = new InputStreamRequestEntity(inputStream, bytes.length, CONTENT_TYPE); postMethod.setRequestEntity(requestEntity); HttpClient httpClient = new HttpClient(); int statusCode = httpClient.executeMethod(postMethod); if (statusCode == 200) { String soapResponseData = postMethod.getResponseBodyAsString(); result.put(RESULTCODE, soapResponseData); result.put(SUCCESS, true); return result; } else { LOGGER.info("soapRequestData 呼叫失敗!錯誤碼:{}", statusCode); } result.put(MSG, "Call fails" + statusCode); result.put(SUCCESS, false); } catch (UnsupportedEncodingException e) { result.put(MSG, "UnsupportedEncodingException"); result.put(SUCCESS, false); LOGGER.error(e.getMessage()); } catch (HttpException e) { result.put(MSG, "Http Request Exception"); result.put(SUCCESS, false); LOGGER.error(e.getMessage()); } catch(ConnectException e) { result.put(MSG, "Connection refused"); result.put(SUCCESS, false); LOGGER.error(e.getMessage()); }catch (Exception e) { result.put(MSG, "Systematic analytic anomaly"); result.put(SUCCESS, false); LOGGER.error(e.getMessage()); } return result; } // 封裝請求的body資料,每一個wsdl都不一樣,可以使用soapui檢視 private String buildRequestData(Map<String, String> patameterMap) { StringBuilder soapRequestData = new StringBuilder(); soapRequestData.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); soapRequestData.append( "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://WebXml.com.cn/\">") .append("<soapenv:Header/>").append("<soapenv:Body>").append("<web:TranslatorString>"); Set<String> nameSet = patameterMap.keySet(); //可能會有多個引數 for (String name : nameSet) { soapRequestData.append("<" + name + ">" + patameterMap.get(name) + "</" + name + ">"); } soapRequestData.append("</web:TranslatorString>"); soapRequestData.append("</soapenv:Body>"); soapRequestData.append("</soapenv:Envelope>"); return soapRequestData.toString(); } }

使用hutool工具

  • 引入開源工具類
    開發客戶端程式碼
/**
 * @author xpy
 * hutool地址:http://hutool.mydoc.io/undefined#category_76217
 */
public class EnglishChineseClient {
	public String englishChinese(String word,String url) {
		String body = HttpRequest.post(url)
		.header("Content-Type", "application/x-www-form-urlencoded")
		.form("wordKey", word)
		.timeout(2000)
		.execute().body();
		return body;
	}

}

使用feign

  • 引入jar包
public class FeignApi {
	public String englishChinese(String word) {
		RemoteService service = Feign.builder()
				.encoder((o,type,template)->{
					JSONObject json = JSONUtil.parseObj(o);
					String data = buildRequestData(json);
					template.body(data);
				})
				.decoder((response,type)->{
					Decoder.Default d = new Decoder.Default();
					return d.decode(response, type);
				})
				.target(RemoteService.class,"http://fy.webxml.com.cn");
		
		return service.getChinese(word);
	}
	private String buildRequestData(JSONObject json) {
        StringBuilder soapRequestData = new StringBuilder();
        soapRequestData.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        soapRequestData.append(
                "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://WebXml.com.cn/\">")
                .append("<soapenv:Header/>").append("<soapenv:Body>").append("<web:TranslatorString>");
        Set<String> nameSet = json.keySet();
        //可能會有多個引數
        for (String name : nameSet) {
            soapRequestData.append("<" + name + ">" + json.get(name) + "</" + name + ">");
        }
        soapRequestData.append("</web:TranslatorString>");
        soapRequestData.append("</soapenv:Body>");
        soapRequestData.append("</soapenv:Envelope>");
        return soapRequestData.toString();
    }
}

介面

public interface RemoteService {
	@RequestLine("POST /app/know/xxx")
	@Headers("Content-Type: application/json")
	String getCust(String params);
	
	@RequestLine("POST /webservices/EnglishChinese.asmx")
	@Headers("Content-Type: text/xml")
	String getChinese(@Param(value = "web:wordKey") String wordKey);
}

原始碼檔案:https://github.com/xingpeiyue/tif
總結:使用axis2生成的程式碼,冗餘量大,當測試環境的action和現網的action不一樣時,導致出錯