最近公司派我出差与乙方公司对接接口,开发了将近大半年的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 请求 后续更新.....
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.cabbage.spring.commons.exception.TsException;
import com.cabbage.spring.contants.KeyConstant;
import com.cabbage.spring.tools.redis.utils.RedisRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;
public JSONObject getHttp(String name,String nameTwo){
try {
HttpRequest request= HttpUtil.createGet(MERGED_URL+getName(name,nameTwo));
String result=request.timeout(2000).execute().body();
if(StringUtils.isNotEmpty(result)){
JSONObject obj = JSONObject.parseObject(result);
if (obj.get("status").equals("ok")) {
return obj.getJSONObject("tick");
}
}
}catch (Exception e){
throw new TsException("获取失败");
}
return null;
}