JAVA调用远程接口
介绍一下JAVA调用远程接口获取数据。一般业务中主要用到的就是get和post的方式。其他的方式,以后用到了,再补充。
啰嗦一下get和post方式不同点.如果只说使用功能,那么下面几句话就够了,如果要深究为什么这样,那么可以参考这篇博客,讲解的清晰易懂:https://www.cnblogs.com/logsharing/p/8448446.html
Get:将参数放在URL后面,全部信息被暴露不安全,参数编码有限制,URL长度有限制。
POST:将请求参数通过BODY传送,安全的,且参数编码和长度无限制。
好了,下面是我用GET和POST调用远程接口的两个例子,注释的很清楚。首先使用CloseHttpClient需要引用jar。
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
Get方式远程请求调用接口
@Override
public String getSecondPBOC(String applicationNumber) {
InputStream is = null;
String body = null;
StringBuilder res = new StringBuilder();
// 实例化CloseableHttpClient
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
// 添加URL和请求参数
URIBuilder ub = new URIBuilder(secondPBOCURL);
ub.setParameter("applicationNumber", applicationNumber);
// 使用get方法添加URL
HttpGet get = new HttpGet(ub.build());
// 设置请求超时时间
RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).build();
get.setConfig(config);
//使用http调用远程,获取相应信息
response = client.execute(get);
// 获取响应状态码,可根据是否响应正常来判断是否需要进行下一步
int statusCode = response.getStatusLine().getStatusCode();
// 获取响应实体
HttpEntity entity = response.getEntity();
// 读取响应内容
if (entity != null) {
is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is, Consts.UTF_8));
while ((body = br.readLine()) != null) {
res.append(body);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return res.toString();
}
以下是使用POST方法调用远程接口获取信息的,其中我的请求参数是XML报文的,所以前期先使用dom4j生成了一下请求参数。添加依赖。
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
</dependency>
POST方式调用远程接口
@Override
public String getSecondPBOCReport(String applicationNumber, String idNumber, String idType, String chineseName) {
//格式化时间,生成渠道代码
SimpleDateFormat format=new SimpleDateFormat("YYYYmmDDHHMMSSFFFF");
String chnlTxNo=format.format(new Date());
//实例化文档
Document document = DocumentHelper.createDocument();
//添加节点
Element service = document.addElement("request");
Element head = service.addElement("head");
Element body = service.addElement("Proc_Query");
//设置节点内容
head.addElement("Chnl_Tx_No").setText(chnlTxNo);
head.addElement("Sys_Code").setText(sysCode);
head.addElement("Txn_Code").setText(txnCode);
body.addElement("User_Name").setText(Base64Util.decodeBase64(userName));
body.addElement("User_Password").setText(Base64Util.decodeBase64(userPassword));
body.addElement("Application_Number").setText(applicationNumber);
body.addElement("Id_Number").setText(idNumber);
body.addElement("Id_Type").setText(idType);
body.addElement("Chinese_Name").setText(chineseName);
body.addElement("Query_reason").setText(queryReason);
//生成XML报文
log.info("request="+document.asXML());
InputStream is = null;
String responseBody = null;
StringBuilder res = new StringBuilder();
//实例化HttpClient
CloseableHttpClient client = HttpClients.createDefault();
//使用POST方法
HttpPost post = new HttpPost(reportURL);
//设置httpPost的请求头中的MIME类型为xml
post.setHeader("Content-Type", "application/xml");
//添加请求body的内容,就是我的请求参数,不再拼接到URL尾部
post.setEntity(new StringEntity(document.asXML(),"utf-8"));
CloseableHttpResponse response = null;
try {
//设置信息超时时间
RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).build();
post.setConfig(config);
//调用远程接口,获取返回信息
response = client.execute(post);
//获取响应实体
HttpEntity entity = response.getEntity();
//读取响应内容
if (entity != null) {
is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is, Consts.UTF_8));
while ((responseBody = br.readLine()) != null) {
res.append(responseBody);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return res.toString();
}
一般调用远程接口这样就可以了。
可以自己写一个接口来测试调用一下。下面是我用于测试POST方法获取报文的servlet,记下来自己下次测试备用。
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取请求参数
BufferedReader reader1 = new BufferedReader(new InputStreamReader(request.getInputStream()));
String str = "";
String reqContent = "";
while ((str = reader1.readLine()) != null) {
reqContent += str;
}
// 读取本地文件,返回文件内容
File file = new File("D:\\text.html");
BufferedReader reader = null;
StringBuffer sbf = new StringBuffer();
try {
InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8");
reader = new BufferedReader(read);
String tempStr;
while ((tempStr = reader.readLine()) != null) {
sbf.append(tempStr);
}
reader.close();
} catch (IOException e) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
// 返回post的请求内容
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Type", "application/text, charset=UTF-8");
PrintWriter out = response.getWriter();
out.print(sbf.toString());
out.flush();
out.close();
}