主流协议包括Http协议和Webservice(soap)协议
http:是标准超文本传输协议
SOAP简单对象访问协议:是一种轻量的、简单的、基于 XML 的协议,它被设计成在 WEB 上交换结构化的和固化的信息
Http协议调用方式:
Webservice协议调用方式:
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
使用方式步骤:
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;
}
}
1、Wsimport命令生成客户端
使用jdk1.7以上的版本生成
wsimport -d D:\test -keep -verbose http://localhost:8080/ht_service/services/certsercureService?wsdl
这里简介一下參数:
将生成的代码放到项目中,调用相关方法。
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;
}
}