最近公司派我出差与乙方公司对接接口,开发了将近大半年的App,突然有冲突,所以整合一下,此处省略十万八千字......
言归正传,怎么通过java调用别人写的接口了?我们在网上看到大部分都是有点麻烦的,其实我们可以通过 RestTemplate
进行开发,常用的http基本请求方式都有 Get,Post ,Put ,Delete,等等
我这里的是post请求,参数中含有 list 的,map传参
首先我们创建一个配置类
package com.japhet.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration(value = "config2")
public class Config {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
@Resource
private RestTemplate restTemplate;
// 核心
public String doPost(String url,Map<String, Object> params) throws Exception {
JSONObject jsonObject = restTemplate.postForObject(url,params,JSONObject.class);
return jsonObject.toString();
}
//调用
public static void main(String[] args) {
if(true){//自己业务
for(int i=0;i<10;i++){
stringList.add("参数"+i);
}
}else{
stringList.add("参数1");
}
JSONArray jsonArray = JSONArray.fromArray(new ArrayList[]{stringList});
String listJson = jsonArray.toString();
map.put("xxx", "参数1");
map.put("xxx", listJson);
map.put("xxx", "参数1");
map.put("xxx", "参数1");
map.put("xxx", "参数1");
try{
String result = doPost("接口路径",map);
}catch (Exception e){
e.printStackTrace();
}
}
get 请求 后续更新.....
来源:CSDN
作者:Japhet_jiu
链接:https://blog.csdn.net/Japhet_jiu/article/details/103999631