总结几种访问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不一样时,导致出错

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值