实践1: 项目A调用外网接口B并实现内容解析;
实践2: 外网接口C访问接口B并响应内容;
一、实践1
实现httpclient工具类供后续调用
public class HttpClientUtil {
public static final String PCAC_API_BASE_URL = "http://100.247.60.83:8080/ries_interface/httpServlet";
private static CloseableHttpClient httpclient = null;
static final int connectionRequestTimeout = 5000;// ms毫秒,从池中获取链接超时时间
static final int connectTimeout = 5000;// ms毫秒,建立链接超时时间
static final int socketTimeout = 30000;// ms毫秒,读取超时时间
static final int maxTotal = 500;// 最大总并发,很重要的参数
static final int maxPerRoute = 100;// 每路并发,很重要的参数
public static CloseableHttpClient getHttpClient() {
if (null == httpclient) {
synchronized (HttpClientUtil.class) {
if (null == httpclient) {
httpclient = init();
}
}
}
return httpclient;
}
/**
* 链接池初始化
* @return
*/
private static CloseableHttpClient init() {
CloseableHttpClient newHttpclient = null;
// 设置连接池
ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
Registry registry = RegistryBuilder. create().register("http", plainsf).register("https", sslsf).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
// 将最大连接数增加
cm.setMaxTotal(maxTotal);
// 将每个路由基础的连接增加
cm.setDefaultMaxPerRoute(maxPerRoute);
// 请求重试处理
HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
if (executionCount >= 2) {// 如果已经重试了2次,就放弃
return false;
}
if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
return true;
}
if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
return false;
}
if (exception instanceof InterruptedIOException) {// 超时
return false;
}
if (exception instanceof UnknownHostException) {// 目标服务器不可达
return false;
}
if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
return false;
}
if (exception instanceof SSLException) {// SSL握手异常
return false;
}
HttpClientContext clientContext = HttpClientContext.adapt(context);
HttpRequest request = clientContext.getRequest();
// 如果请求是幂等的,就再次尝试
if (!(request instanceof HttpEntityEnclosingRequest)) {
return true;
}
return false;
}
};
// 配置请求的超时设置
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(connectionRequestTimeout)
.setConnectTimeout(connectTimeout)
.setSocketTimeout(socketTimeout)
.build();
newHttpclient = HttpClients.custom()
.setConnectionManager(cm)
.setDefaultRequestConfig(requestConfig)
.setRetryHandler(httpRequestRetryHandler)
.setConnectionManagerShared(true)
.build();
return newHttpclient;
}
/**
* 数据提交
* @param url
* @param params
* @return
*/
public static String postData(String url,Map params){
String responseResult = "";
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = null;
try {
httpClient = getHttpClient();
HttpPost httpPost = new HttpPost(url);
//请求参数
List nvps = null;
if (params != null && !params.isEmpty()) {
nvps = new ArrayList(params.size());
for (Map.Entry entry : params.entrySet()) {
String value = entry.getValue();
if (value != null) {
nvps.add(new BasicNameValuePair(entry.getKey(), value));
}
}
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
response = httpClient.execute(httpPost);
InputStream in = response.getEntity().getContent();
int responseCode = response.getStatusLine().getStatusCode();
if(responseCode == 200){
HttpEntity responseEntity = response.getEntity();
responseResult = EntityUtils.toString(responseEntity);
}
//将用完的连接释放,下次请求可以复用
in.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
//httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return responseResult;
}
}
获取对方的响应结果并解析
public class XmlUtil {
public static String sendPackagedRequestXML_httpClient(String requestXML) throws Exception {
Map params = new HashMap();
params.put("xml", requestXML);
String result = HttpClientUtil.postData(HttpClientUtil.PCAC_API_BASE_URL,params);
return result;
}
public static void main(String[] args){
try {
//请求接口获取响应结果
String requestXML = "V1.0.1 201805280000000001 R0001 LR0001 20180528102612 111111 ";
String responseResult = sendPackagedRequestXML_httpClient(requestXML);
System.out.println("responseResult--------" + responseResult);
//解析响应内容
StringReader reader = new StringReader(responseResult);
InputSource source = new InputSource(reader);
SAXBuilder saxBuilder = new SAXBuilder();
Document doc = saxBuilder.build(source);
Element root = doc.getRootElement();
Element element1 = root.getChild("Respone");
Element element2 = root.getChild("Signature");
System.out.println("root--------" + root.toString());
System.out.println("element1--------" + element1.toString());
System.out.println("element2--------" + element2.toString());
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
结果呈现:
responseResult--------V1.0.1 201805280000000001 R0001 LR0001 20180531125651 111111 02 H00001 kdyAmpKeXJ4GWQWv7M1WFZn7qnya9ixzwKC0p7W79KKV10eibBWY0WT21L3wuHHR5aRREhJTuDRChLW5l9RyNTZX1DxML3V7jnLvFB6VYJN41CKkBnqMj/SKnnQZe3c6YbrevikT4yDy6oEyZmAb87WTaSko0Qf/W3E2cqvVNUZCeij/ubjZJvUKtMTdYLwgCs04aWjDZWkrWGIXuoNRUtE4Bi/3ReuaUHQsYT7ioLWJR3qRQtKWQ9HNfApdrwVbqU2NtkNq0NVW3FMwEG9opxQuVfh/UDaFg86e5dXSqYe74Q8OfkaKn8SC+aHJ2URaFH1F3Lc8n5kXW2Y0bMLwQw==
root--------[Element: ]
element1--------[Element: ]
element2--------[Element: ]
二、实践2
提供接口给对方,需要将接口开放进行IP外网映射配置,例如提供给对方的接口为http://ip:port/project/infoPush/test 对方请求结果即为responseResult内容。
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
@RestController
@RequestMapping("/project/infoPush")
public class PushService {
@SuppressWarnings("unchecked")
@RequestMapping(value = "/test")
public String test(@RequestBody String paramsStr) {
Map params = (Map) JSONObject.parse(paramsStr);
String xml = (String) params.get("xml");
String rand = (String) params.get("rand");
System.out.println("xml=>"+xml);
System.out.println("rank=>"+rand);
String responseResult = "处理后的响应内容";
return responseResult;
}
}
以上是简单示例,其中请求方式为post,传递的参数均为xml字符串类型,引入的jar包分别为httpcore-4.4.4.jar、httpclient-4.5.2.jar、commons-logging-1.0.3.jar、jdom-2.0.5.jar。