当前位置:网站首页>外围系统调用SAP的WebAPI接口
外围系统调用SAP的WebAPI接口
2022-07-25 12:46:00 【panda_225400】
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
前言
提示:这里可以添加本文要记录的大概内容:
公司要换新的SAP,之前调用SAP的接口都是通过WebService方式,现在新的SAP需要换成WebAPI接口
提示:以下是本篇文章正文内容,下面案例可供参考
一、WebAPI 和 WebService的区别是什么?
WebAPI :
- 无状态,开源,部署在IIS和应用程序上
- 基于HTTP协议,数据格式为纯文本,Response可以被Web API的MediaTypeFormatter转换成任何格式,常用Json格式
- 基于HTTP构建的一个轻量级框架。非常适合移动端客户端服务
- api类似于cs架构,用的协议和端口,是根据开发人员定义的。 需要同时开发客户端API和服务器端程序
WebService :
- 有状态,不开源,只能部署在IIS上
- 基于Soap协议,只支持HTTP协议,数据格式为XML,
- 类似于bs架构,只需要开发服务器端,不需要开发客户端,客户端只要遵循soap协议,就可以调用
所有的WebService都是WebAPI,但所有的WebAPI并不是WebService。Web API的客户端系统(调用者)和服务系统(提供者)彼此独立,调用者可以轻易的使用不同的语言(Java,Python,Ruby等)进行API的调用。Web Service通常仅在两个系统之间交互,几乎总是依赖于类似XML-RPC的接口来相互通信,并且不同的客户端下各浏览器对XML的解析方式不一致,需要重复编写很多代码
。Web Service更加适合为端到端的场景提供服务,Web API则更加适合为应用到应用的场景提供服务。具体网上可查
二、使用步骤
1.C#调用SAP的WebAPI接口
Get提交代码如下(示例):
string result = string.Empty;
var client = new HttpClient();
var strPostUrl = "http://***.**.*.***:8000/sap/bc/rest/z_pda_cbzx_srv?sap-client=300&sap-language=ZH&bukrs=1040";
using (HttpResponseMessage responseMessage = client.Get(strPostUrl))
{
responseMessage.EnsureStatusIsSuccessful();
result = responseMessage.Content.ReadAsString();
}
Response.Write(result);
Post提交代码如下(示例):
string result = string.Empty;
var client = new HttpClient();
var credentials = username + ":" + password;
var base64Credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));
client.DefaultHeaders.Add("Authorization", "Basic " + base64Credentials);
var strPostUrl = "http://***.**.*.***:8000/sap/bc/rest/z_conftab_srv?sap-client=300&sap-language=ZH";
var postData = new {
action_id = "U", stage = "PLATING", work_step = "PL04-RPXXXXX", seg_attr = "BP" };
System.Web.Script.Serialization.JavaScriptSerializer jss = new JavaScriptSerializer();
HttpContent content = HttpContent.Create(Encoding.UTF8.GetBytes("["+jss.Serialize(postData)+"]"), "application/json");
using (HttpResponseMessage responseMessage = client.Post(strPostUrl, content))
{
responseMessage.EnsureStatusIsSuccessful();
result = responseMessage.Content.ReadAsString();
}
Response.Write(result);
2.Python调用SAP的WebAPI接口
Get提交代码如下(示例):
url='http://***.**.*.***:8000/sap/bc/rest/z_pda_cbzx_srv?sap-client=300&sap-language=ZH&bukrs=1040'#存储API调用的URL
r=requests.get(url) #获得URL对象
print("Status code:",r.status_code) #判断请求是否成功(状态码200时表示请求成功)
if r.status_code == 200:
response_dict = r.json() # API返回json格式的信息(将响应存储到变量中)\
print(response_dict)
else:
print("调用 web-api 异常")
POST提交代码如下(示例):
credentials = username + ":" + password
auth = str(base64.b64encode(credentials.encode('utf-8')), 'utf-8')
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0', "Content-Type": "application/json", 'Authorization': f'Basic {auth}'}
url_json = 'http://***.**.*.***:8000/sap/bc/rest/z_conftab_srv?sap-client=300&sap-language=ZH'
data_json = json.dumps({
'action_id':'U','stage':'PLATING','work_step':'PL04-RPXXXXX','seg_attr':'BP'}) # dumps:将python对象解码为json数据
print("["+data_json+"]")
r_json = requests.post(url_json, "["+data_json+"]", headers=headers)
print("Status code:",r_json.status_code)
print(r_json)
print(r_json.text)
print(r_json.content)
3.Java调用SAP的WebAPI接口
Get提交代码如下(示例):
CloseableHttpClient client = HttpClients.createDefault();
URIBuilder uriBuilder = new URIBuilder("http://***.**.*.***:8000/sap/bc/rest/z_pda_cbzx_srv?sap-client=300&sap-language=ZH&bukrs=1040");
//创建httpGet远程连接实例,这里传入目标的网络地址
HttpGet httpGet = new HttpGet(uriBuilder.build());
// 设置请求头信息,鉴权(没有可忽略)
//httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
// 设置配置请求参数(没有可忽略)
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
.setConnectionRequestTimeout(35000)// 请求超时时间
.setSocketTimeout(60000)// 数据读取超时时间
.build();
// 为httpGet实例设置配置
httpGet.setConfig(requestConfig);
//执行请求
CloseableHttpResponse response = client.execute(httpGet);
//获取Response状态码
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
//获取响应实体, 响应内容
HttpEntity entity = response.getEntity();
//通过EntityUtils中的toString方法将结果转换为字符串
String str = EntityUtils.toString(entity);
System.out.println(str);
response.close();
client.close();
Post提交代码如下(示例):
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// 创建httpPost远程连接实例
HttpPost post = new HttpPost("http://***.**.*.***:8000/sap/bc/rest/z_conftab_srv?sap-client=300&sap-language=ZH");
String credentials = userName + ":" + password;
String encoding = DatatypeConverter.printBase64Binary(credentials.getBytes("utf-8")); //username password 自行修改 中间":"不可少
post.setHeader("Authorization", "Basic " + encoding);
String result = "";
try (CloseableHttpClient closeableHttpClient = httpClientBuilder.build()) {
String jsonPrarms = "{\"action_id\":\"U\",\"stage\":\"PLATING\",\"work_step\":\"PL04-RPXXXXX\",\"seg_attr\":\"BP\"}";
System.out.println("["+jsonPrarms.toString()+"]");
HttpEntity entityParam = new StringEntity("["+jsonPrarms.toString()+"]", "UTF-8");
post.setEntity(entityParam);
post.setHeader("Content-type", "application/json");
HttpResponse resp = closeableHttpClient.execute(post);
StatusLine statusLine = resp.getStatusLine(); //获取请求对象中的响应行对象
int responseCode = statusLine.getStatusCode();
if (responseCode == 200) {
//获取响应信息
HttpEntity entity = resp.getEntity();
InputStream input = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(input,"utf-8"));
String str1 = br.readLine();
System.out.println("服务器的响应是:" + str1);
br.close();
input.close();
} else {
System.out.println("响应失败");
}
} catch (IOException e) {
e.printStackTrace();
}
总结
记录点点滴滴
边栏推荐
- How to use causal inference and experiments to drive user growth| July 28 tf67
- LeetCode 0133. 克隆图
- Eccv2022 | transclassp class level grab posture migration
- massCode 一款优秀的开源代码片段管理器
- Atcoder beginer contest 261e / / bitwise thinking + DP
- 零基础学习CANoe Panel(12)—— 进度条(Progress Bar)
- B tree and b+ tree
- Clickhouse notes 03-- grafana accesses Clickhouse
- 【CSDN 年终总结】结束与开始,一直在路上—— “1+1=王”的2021总结
- 吕蒙正《破窑赋》
猜你喜欢

Chapter5 : Deep Learning and Computational Chemistry

The larger the convolution kernel, the stronger the performance? An interpretation of replknet model

Selenium use -- installation and testing

零基础学习CANoe Panel(12)—— 进度条(Progress Bar)

Leetcode 0133. clone diagram

艰辛的旅程
![[300 opencv routines] 239. accurate positioning of Harris corner detection (cornersubpix)](/img/a6/c45a504722f5fd6e3c9fb8e51c6bb5.png)
[300 opencv routines] 239. accurate positioning of Harris corner detection (cornersubpix)

基于JEECG制作一个通用的级联字典选择控件-DictCascadeUniversal

Substance Designer 2021软件安装包下载及安装教程

【CSDN 年终总结】结束与开始,一直在路上—— “1+1=王”的2021总结
随机推荐
手写一个博客平台~第一天
【历史上的今天】7 月 25 日:IBM 获得了第一项专利;Verizon 收购雅虎;亚马逊发布 Fire Phone
[problem solving] ibatis.binding BindingException: Type interface xxDao is not known to the MapperRegistry.
"Autobiography of Franklin" cultivation
Kyligence was selected into Gartner 2022 data management technology maturity curve report
Can flinkcdc import multiple tables in mongodb database together?
Common operations for Yum and VIM
Business visualization - make your flowchart'run'(3. Branch selection & cross language distributed operation node)
What does the software testing process include? What are the test methods?
If you want to do a good job in software testing, you can first understand ast, SCA and penetration testing
使用vsftpd服务传输文件(匿名用户认证、本地用户认证、虚拟用户认证)
Seven lines of code made station B crash for three hours, but "a scheming 0"
Ministry of Public Security: the international community generally believes that China is one of the safest countries in the world
Chapter5 : Deep Learning and Computational Chemistry
Zero basic learning canoe panel (15) -- CAPL output view
Interviewer: "classmate, have you ever done a real landing project?"
Azure Devops (XIV) use azure's private nuget warehouse
吕蒙正《破窑赋》
pytorch创建自己的Dataset加载数据集
【问题解决】ibatis.binding.BindingException: Type interface xxDao is not known to the MapperRegistry.