接口调用框架

一、接口协议

主流协议包括Http协议和Webservice(soap)协议

http:是标准超文本传输协议

SOAP简单对象访问协议:是一种轻量的、简单的、基于 XML 的协议,它被设计成在 WEB 上交换结构化的和固化的信息

Http协议调用方式:

  • HttpURLConnection:jdk自带,net包
  • HttpClient:Apache公司的产品
  • RestTemplate:Spring提供

Webservice协议调用方式:

  • Wsimport命令生成客户端:java自带
  • HttpClient
  • cxf框架
  • axis2框架

二、Http协议

1、HttpURLConnection

主要为get方式和post方式

/**
 * Get方式
 * @param urlStr
 */
public static String sendGet(String urlStr) {
	String result = "";
	HttpURLConnection connection = null;
	BufferedReader reader = null;
	String line = null;
	try {
		URL url = new URL(urlStr);
		connection = (HttpURLConnection) url.openConnection();// 根据URL生成HttpURLConnection
		connection.setRequestMethod("GET");// 默认GET请求
		connection.setRequestProperty("Accept", "application/json");
		connection.connect();// 建立TCP连接
		if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
			reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 发送http请求
			StringBuilder resultBuilder = new StringBuilder();
			// 循环读取流
			while ((line = reader.readLine()) != null) {
				resultBuilder.append(line).append(System.getProperty("line.separator"));// "\n"
			}
			result = resultBuilder.toString();
			System.out.println(result);
		}
	} catch (IOException e) {
		e.printStackTrace();
	}  finally {
		try {
			if(reader != null) {
				reader.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(connection != null) {
			connection.disconnect();
		}
	}
	return result;
}

/**
 * Post方法
 * @param url
 * @param param
 * @return
 */
public static String sendPost(String url,Map param) {
	String result = "";
	HttpURLConnection connection = null;
	BufferedReader reader = null;
	String line = null;
	try {
		StringBuilder params=new StringBuilder();
		for(Entry entry:param.entrySet()){
			params.append(entry.getKey());
			params.append("=");
			params.append(entry.getValue());
			params.append("&");
		}
		if(params.length()>0){
			params.deleteCharAt(params.lastIndexOf("&"));
		}
		URL restServiceURL = new URL(url+(params.length()>0 ? "?"+params.toString() : ""));
		connection = (HttpURLConnection) restServiceURL.openConnection();
		connection.setRequestMethod("POST");
		connection.setRequestProperty("Accept", "application/json");
		// 设置是否从httpUrlConnection读入,默认情况下是true;    
		connection.setDoInput(true);    
		// Post 请求不能使用缓存    
		connection.setUseCaches(false); 
		if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
			reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 发送http请求
			StringBuilder resultBuilder = new StringBuilder();
			// 循环读取流
			while ((line = reader.readLine()) != null) {
				resultBuilder.append(line).append(System.getProperty("line.separator"));// "\n"
			}
			result = resultBuilder.toString();
			System.out.println(result);
		}else {
			System.out.println(connection.getResponseCode());
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		try {
			if(reader != null) {
				reader.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(connection != null) {
			connection.disconnect();
		}
	}
	return result;
}

 

2、httpclient

jar包下载地址: http://hc.apache.org/downloads.cgi

使用方式步骤:

  1. 创建HttpClient对象。
  2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
  3.  如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HttpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
  4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
  5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
  6.  释放连接。无论执行方法是否成功,都必须释放连接
public static String sendGet(String url) {
	String result = "";
	CloseableHttpClient client = HttpClients.createDefault();  
	HttpGet get = new HttpGet(url);  
	try {
		HttpResponse response = client.execute(get);
		if (response.getStatusLine().getStatusCode() == 200) {  
			HttpEntity resEntity = response.getEntity();  
			result = EntityUtils.toString(resEntity, "utf-8");  
			System.out.println(result);  
		} else {  
			System.out.println("请求失败");  
		}  
	} catch (Exception e) {
		e.printStackTrace();
	}  
	return result;
}

public static String sendPost(String url,Map param) {
	String result = "";
	List formparams = new ArrayList();
	for(String key : param.keySet()) {
		formparams.add(new BasicNameValuePair(key, param.get(key)));  
	}
	CloseableHttpClient client = HttpClients.createDefault();  
	HttpPost post = new HttpPost(url);  
	RequestConfig requestConfig = RequestConfig.custom()  
			.setConnectTimeout(5000)//一、连接超时:connectionTimeout-->指的是连接一个url的连接等待时间  
					.setSocketTimeout(5000)// 二、读取数据超时:SocketTimeout-->指的是连接上一个url,获取response的返回等待时间  
					.setConnectionRequestTimeout(5000)  
					.build();  
	HttpEntity reqEntity;
	try {
		reqEntity = new UrlEncodedFormEntity(formparams, "utf-8");
		post.setEntity(reqEntity);  
		post.setConfig(requestConfig);  
		HttpResponse response = client.execute(post);  
		if (response.getStatusLine().getStatusCode() == 200) {  
			HttpEntity resEntity = response.getEntity();  
			result = EntityUtils.toString(resEntity, "utf-8");  
			System.out.println(result);  
		} else {  
			System.out.println("请求失败");  
		}  
	} catch (Exception e) {
		e.printStackTrace();
	}  
	return result;
}

 /**  
 * 发送http delete请求  
 */    
public static String httpDelete(String url,Map headers){    
	String result = "";
	CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();     
	HttpDelete httpdelete = new HttpDelete(url);    
	//设置header  
	if (headers != null && headers.size() > 0) {  
		for (Map.Entry entry : headers.entrySet()) {  
			httpdelete.setHeader(entry.getKey(),entry.getValue());  
		}  
	}  
	CloseableHttpResponse httpResponse = null;    
	try {    
		httpResponse = closeableHttpClient.execute(httpdelete);    
		HttpEntity entity = httpResponse.getEntity();    
		result = EntityUtils.toString(entity, "utf-8");    
	} catch (Exception e) {    
		e.printStackTrace();    
	}finally{    
		try {    
			httpResponse.close();    
		} catch (IOException e) {    
			e.printStackTrace();    
		}    
	}    
	try {   //关闭连接、释放资源    
		closeableHttpClient.close();    
	} catch (IOException e) {    
		e.printStackTrace();    
	}      
	return result;    
}

3、Spring的RestTemplate

xml配置




	
	




	

实现: 

@Controller
public class RestTemplateAction {
 
    @Autowired
    private RestTemplate template;
 
    @RequestMapping("RestTem")
    public @ResponseBody User RestTem(String method) {
        User user = null;
        //查找
        if ("get".equals(method)) {
            user = template.getForObject(
                    "http://localhost:8080/tao-manager-web/get/{id}",
                    User.class, "呜呜呜呜");
 
            //getForEntity与getForObject的区别是可以获取返回值和状态、头等信息
            ResponseEntity re = template.
                    getForEntity("http://localhost:8080/tao-manager-web/get/{id}",
                    User.class, "呜呜呜呜");
            System.out.println(re.getStatusCode());
            System.out.println(re.getBody().getUsername());
 
        //新增
        } else if ("post".equals(method)) {
            HttpHeaders headers = new HttpHeaders();
            headers.add("X-Auth-Token", UUID.randomUUID().toString());
            MultiValueMap postParameters = new LinkedMultiValueMap();
            postParameters.add("id", "啊啊啊");
            postParameters.add("name", "部版本");
            HttpEntity> requestEntity = new HttpEntity>(
                    postParameters, headers);
            user = template.postForObject(
                    "http://localhost:8080/tao-manager-web/post/aaa", requestEntity,
                    User.class);
        //删除
        } else if ("delete".equals(method)) {
            template.delete("http://localhost:8080/tao-manager-web/delete/{id}","aaa");
        //修改
        } else if ("put".equals(method)) {
            template.put("http://localhost:8080/tao-manager-web/put/{id}",null,"bbb");
        }
        return user;
 
    }
}

三、Webservice协议

1、Wsimport命令生成客户端

使用jdk1.7以上的版本生成

wsimport -d D:\test -keep -verbose  http://localhost:8080/ht_service/services/certsercureService?wsdl

这里简介一下參数:

  • -d 表示输出的文件夹。文件夹必须事先存在,否则导出失败。
  • -keep 表示导出webservice的class文件时是否也导出源码java文件。
  • -verbose verbose表示具体信息。

将生成的代码放到项目中,调用相关方法。

 

2、axis2

相关jar包:https://download.csdn.net/download/u014231646/11367862


    
	
	    org.apache.axis2
	    axis2
	    1.6.2
	
	
	    org.apache.ws.commons.axiom
	    axiom
	    1.2.20
	    pom
	
	
	    org.apache.ws.commons.axiom
	    axiom-api
	    1.2.20
	

    org.apache.ws.commons.axiom
    axiom-impl
    1.2.20


    wsdl4j
    wsdl4j
    1.6.3


    org.apache.ws.xmlschema
    xmlschema-core
    2.2.3


    org.apache.neethi
    neethi
    
    3.1.1


    org.apache.axis2
    axis2-transport-local
    1.7.7


    org.apache.axis2
    axis2-transport-http
    1.7.7


  

需要知道targetNamespace和url

调用方式

private String targetEndpoint;
private String targetNamespace;
/*
 * 调用webservice服务
 * */
private String sendService(String method, Object[] datas , Class[] dataClass){
	try {
		RPCServiceClient client = new RPCServiceClient();
		Options options = client.getOptions();
		options.setTo(new EndpointReference(targetEndpoint));
		options.setTimeOutInMilliSeconds(1000 * 60);// 毫秒单位
		options.setAction(method);
		Object[] response = client.invokeBlocking(new QName(targetNamespace, method),datas, dataClass);
		String results = (String) response[0];
		logger.info("WebService[method:{}][data:{}]的返回结果[{}]",method,datas,results);
		return results;
	} catch (Exception e) {
		logger.error("WebService请求异常, Cause:{}, Message:{}", e.getCause(), e.getMessage());
		e.printStackTrace();
		return null;
	}
}

 

 

 

你可能感兴趣的:(Web框架及插件)