最早写过一篇相关的博客,但是后来个人觉得并不是一个好方法,而且局限性特别大,因为参数的问题,不能做到公共方法使用,
下面使用了两种方法是前段时间写的,并且测试有效,推荐使用这种方法。
先下载一个接口测试工具SoapUI:https://www.soapui.org/downloads/latest-release.html
打开就长这个样子,无论什么接口,URL最后都要加上?wsdl
测试一个接口,
方法一,公共方法:
HttpClientUtils.java
package com.portal.aspwfcontroller;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Classname HttpClientUtils
* @Description get/Post公共方法
* @Date 2019/6/21 16:38
* @Created by lixiaobei
* @Version TODO
*/
@RestController
public class HttpClientUtils {
/**
*
* @param Url 接口地址
* @param ContentType 请求类型
* @param param 参数集合
*/
public void doGet(String Url,String ContentType,Map<String,Object> param) {
String result = null;
String requestUrl = null;
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
StringBuilder sb = new StringBuilder();
if (param != null)
{
for (Object val : param.keySet())
{
sb.append(val + "=" + param.get(val).toString());
sb.append("&");
}
}
//获取参数。拼接url
if ("".equals(sb))
{
requestUrl = Url;
}else {
requestUrl = Url + "?" + sb.substring(sb.lastIndexOf("&")).toString();
}
// 创建Get请求
HttpGet httpGet = new HttpGet(requestUrl);
httpGet.setHeader("Content-Type",ContentType);
// 响应模型
CloseableHttpResponse response = null;
try {
// 由客户端执行(发送)Get请求
response = httpClient.execute(httpGet);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
log.info("响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
log.info("响应内容为:" + EntityUtils.toString(responseEntity));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* POST请求
* @throws UnsupportedEncodingException
*/
public void doPost(String Url,String ContentType,String SoapAtion,Map<String,Object> param) throws UnsupportedEncodingException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建Post请求
HttpPost httpPost = new HttpPost(Url);
//装填参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if(param != null){
for (Object item : param.keySet())
{
nvps.add(new BasicNameValuePair(item.toString(),param.get(item).toString()));
}
}
//设置参数到请求对象中
httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
httpPost.setHeader("Content-Type",ContentType);
httpPost.setHeader("SOAPAction",SoapAtion);
// 响应模型
CloseableHttpResponse response = null;
try {
// 由客户端执行(发送)Post请求
response = httpClient.execute(httpPost);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
log.info("响应内容为:" + EntityUtils.toString(responseEntity));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
S* @author lixiaobei
* @param wsdlURL 服务地址
* @param SOAPActionUrl 标识头
* @param content 请求内容
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String doHttpPostWCF(String wsdlURL, String SOAPActionUrl,String content)
throws ClientProtocolException, IOException {
// 获得Http客户端
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建Post请求
HttpPost httpPost = new HttpPost(wsdlURL);
StringEntity entity = new StringEntity(content.toString(), "UTF-8");
// 将数据放入entity中
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
httpPost.addHeader("SOAPAction", SOAPActionUrl);
// 响应模型
CloseableHttpResponse response = null;
String result = null;
try {
// 由客户端执行(发送)Post请求
response = httpClient.execute(httpPost);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
result = EntityUtils.toString(responseEntity);
}
} finally {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
}
return result;
}
}
用到方法的地方
//这里使用Map拼接参数,注意:参数的顺序一定要和被请求的接口参数一致
Map<String,Object> map = new LinkedHashMap<String, Object>();
/**
* 接口名称
*/
//Wcf 接口样例
String url = "http://localhost/SvcWcFlow/SvcWorkflowWFBusiness_HR.svc";
/**
* 接口方法
*/
//Wcf 方法样例
String method = "http://tempuri.org/ISvcWFBusiness_HR/hr_TB_WCSQ_UpdateBillNoandPid";
//请求方式
String request = "post";
//若外部接口是get的请求方式
if ("get".equals(request) || "GET".equals(request))
{
httpClientUtils.doGet(url,"application/json;charset=UTF-8",map);
}else if ("post".equals(request) || "POST".equals(request))
{
if (url.endsWith(".svc"))
{
StringBuffer xMLcontent = new StringBuffer();
xMLcontent.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">" +
" <soapenv:Header/>" +
" <soapenv:Body>");
xMLcontent.append("<tem:" + (method.substring(method.lastIndexOf("/") + 1)) + ">");
for (Object item : map.keySet())
{
xMLcontent.append("<tem:" + item + ">" + map.get(item).toString() + "</tem:" + item + ">");
}
xMLcontent.append("</tem:" + (method.substring(method.lastIndexOf("/") + 1)) + ">");
xMLcontent.append("</soapenv:Body>" +
"</soapenv:Envelope>");
String responseXML = doHttpPostWCF(url,method,xMLcontent.toString());
OMElement omElement = OMXMLBuilderFactory.createOMBuilder(new ByteArrayInputStream(responseXML.getBytes()), "utf-8").getDocumentElement();
Iterator<OMElement> it = omElement.getFirstElement().getFirstElement().getChildElements();
while (it.hasNext()) {
OMElement element = it.next();
result = element.getText();
log.info(element.getText());
}
}else if (url.endsWith(".asmx"))
{
httpClientUtils.doPost(url + method.substring(method.lastIndexOf("/")),
"application/x-www-form-urlencoded",
method,map);
}
}
这是方法一,优点是可以做成公有方法,推荐
方法二,直接拷贝这个结构体:
doHttpPostByHttpClient.java
package com.portal.controller;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class PortalHttpServiceUtils {
/**
* HTPP请求公用接口,用以调用外部服务
* @author lizhixian
* @param wsdlURL 服务地址
* @param contentType 请求类型
* @param SOAPActionUrl 标识头
* @param content 请求内容
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public String doHttpPostByHttpClient(String wsdlURL, String contentType,String SOAPActionUrl,String content)
throws ClientProtocolException, IOException {
// 获得Http客户端
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建Post请求
HttpPost httpPost = new HttpPost(wsdlURL);
StringEntity entity = new StringEntity(content.toString(), "UTF-8");
// 将数据放入entity中
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", contentType);
httpPost.addHeader("SOAPAction", SOAPActionUrl);
// 响应模型
CloseableHttpResponse response = null;
String result = null;
try {
// 由客户端执行(发送)Post请求
response = httpClient.execute(httpPost);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
//System.out.println("响应ContentType为:" + responseEntity.getContentType());
//System.out.println("响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
result = EntityUtils.toString(responseEntity);
//System.out.println("响应内容为:" + result);
}
} finally {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
}
return result;
}
}
/**
* 获取用户信息
* @param userlogin
* @return
*/
public String GetUser(String userlogin) throws IOException {
String User = null;
String SOAPActionUrl = "http://tempuri.org/IService/GetUserJson";
StringBuffer xMLcontent = new StringBuffer();
xMLcontent.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">" +
" <soapenv:Header/>" +
" <soapenv:Body>" +
" <tem:GetUserJson>" +
" <tem:loginName>" + userlogin +"</tem:loginName>" +
" </tem:GetUserJson>" +
" </soapenv:Body>" +
"</soapenv:Envelope>");
String responseXML = httpServiceUtils.doHttpPostByHttpClient(WSDLlURL,SOAPActionUrl,xMLcontent.toString());
OMElement omElement = OMXMLBuilderFactory.createOMBuilder(new ByteArrayInputStream(responseXML.getBytes()), "utf-8").getDocumentElement();
Iterator<OMElement> it = omElement.getFirstElement().getFirstElement().getChildElements();
while (it.hasNext()) {
OMElement element = it.next();
User = element.getText();
}
return User;
}
这样也是可以的。