一、前言
由于项目从企业获取数据需要通过sap接口进行传输,并且请求参数是xml格式,以下是使用java来实现对sap接口的调用。
二、导入依赖
在pom.xml文件中添加依赖
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.8.0</version>
</dependency>
三、sap接口工具类
import org.apache.commons.net.util.Base64;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
/**
* SAP请求接口工具类
*/
public class SapReqUtil {
/**
* sap请求接口
* @param reqUrl 请求url地址
* @param xml 请求xml格式参数
* @return xml格式返回值
*/
public static String invokeSap(String reqUrl, String xml) throws IOException {
// 创建指定链接的url对象
URL url = new URL(reqUrl);
// 建立到url对象之间的链接
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//设置sap接口提供的用户名和密码
String username = "用户名";
String password = "密码";
String auth = username + ":" + password;
//对其进行加密
byte[] rel = Base64.encodeBase64(auth.getBytes());
String res = new String(rel);
//设置认证属性
con.setRequestProperty("Authorization", "Basic " + res);
// 如果打算使用 URL 连接进行输出,则将 DoOutput 标志设置为 true
con.setDoOutput(true);
// 设置请求的数据内容不被存储
con.setRequestProperty("Cache-Control", "no-cache");
// 设置请求的字符集编码格式
con.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
con.setRequestMethod("POST");
// 构造向指定链接写入数据的的输出流
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
// 向指定链接写入数据
out.write(new String(xml));
out.flush();
out.close();
// 将从服务端返回的数据读取到内存中
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = "";
// 构造一个空的StringBuffer对象,用于存储内存中的数据
StringBuffer buf = new StringBuffer();
for (line = br.readLine(); line != null; line = br.readLine()) {
// 由于服务端返回的数据的字符集编码有可能不是UTF-8,需要对返回的数据通过指定的字符集进行解码
buf.append(new String(line.getBytes(), StandardCharsets.UTF_8));
}
br.close();
return buf.toString();
}
}
四、使用
// Service层代码
@Override
public String sapTask() throws IOException {
String reqUrl = "sap请求url";
String xml = "xml格式入参";
// 调用SAP接口,返回xml字符串
String xmlString = SapReqUtil.invokeSap(reqUrl,xml);
// 对返回的数据进行xml解析,进行具体的业务处理
// 比如转成json对象...
}