总结几种访问webservice接口的方式

使用axis2

  • 下载axis2-1.6.4 axis2-1.6.4
  • 解压在bin目录下运行:wsdl2java -uri http://fy.webxml.com.cn/webservices/EnglishChinese.asmx?wsdl -p com.xing.tif.axis2.cient -o H:\axis
  • 将生成的资源文件(java)拷贝到项目中
    总结几种访问webservice接口的方式_第1张图片
    使用开源的webservice地址:http://fy.webxml.com.cn/webservices/EnglishChinese.asmx
    调用客户端代码:
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("");
        soapRequestData.append(
                "")
                .append("").append("").append("");
        Set<String> nameSet = patameterMap.keySet();
        //可能会有多个参数
        for (String name : nameSet) {
            soapRequestData.append("<" + name + ">" + patameterMap.get(name) + " + name + ">");
        }
        soapRequestData.append("");
        soapRequestData.append("");
        soapRequestData.append("");
        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("");
        soapRequestData.append(
                "")
                .append("").append("").append("");
        Set<String> nameSet = json.keySet();
        //可能会有多个参数
        for (String name : nameSet) {
            soapRequestData.append("<" + name + ">" + json.get(name) + " + name + ">");
        }
        soapRequestData.append("");
        soapRequestData.append("");
        soapRequestData.append("");
        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不一样时,导致出错

你可能感兴趣的:(JAVAWEB,JAVA)