Springboot调用第三方接口

2023-02-18 00:00:00 调用 第三方 接口

方式一:使用RestTemplate请求第三方接口

配置yaml配置文件

server:
  port: 8081
# 第三方接口
interfaceurl:
  REQUEST_URL: http://192.168.5.178:8080/query/
  

RestTemplate配置类

/** * RestTemplate配置类 */
@Configuration
public class RestTemplateConfig { 
    @Autowired
    private RestTemplateBuilder restTemplateBuilder;
    @Bean
    public RestTemplate restTemplate(){ 
        return restTemplateBuilder.build();
    }
}

接口类

@Controller
@Slf4j
public class InterfaceController { 
    @Autowired
    private InterfaceServiceImpl interfaceService;
    //去请求第三方的key
    @RequestMapping("/select/{key}")
    @ResponseBody
    public String queryInterface(@PathVariable("key") String key){ 
        log.info("传递进来的key为===>"+key);
        //使用service调用第三方接口,并返回对象
        Status status = interfaceService.queryByKey(key);
        //将对象转化为json字符串
        String s = JSONObject.toJSONString(status);
        return s;
    }
}

service接口类

public interface InterfaceService { 
    //根据key查询
    Status queryByKey(String key);
}

service接口实现类

@Service
@Slf4j
public class InterfaceServiceImpl implements InterfaceService { 
    @Autowired
    private InterfaceUrl interfaceUrl;
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public Status queryByKey(String key) { 
        //用RestTemplate请求第三方接口
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(interfaceUrl.getREQUEST_URL() + key, String.class);
// log.info("这个forEntity=====>" + responseEntity);
        //获取请求body
        String body = responseEntity.getBody();
        ObjectMapper objectMapper = new ObjectMapper();
        Status status = new Status();
        try { 
            //转化为对象
            status = objectMapper.readValue(body, Status.class);
        } catch (JsonProcessingException e) { 
            e.printStackTrace();
// log.info("转化异常");
        }
        return status;
    }
}

三个实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Status implements Serializable { 
    private Integer code;
    private String msg;
    private List<AutoComplete> data;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
@ConfigurationProperties("interfaceurl")
public class InterfaceUrl { 
    private String REQUEST_URL;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AutoComplete implements Serializable { 
    private String value;
    private String buildID;
}

方式二:采用HttpURLConnection工具请求第三方接口

工具类HttpUtil

public class HttpUtil { 
    /** * 模拟浏览器的请求 * * @param httpURL 发送请求的地址 * @param params 请求参数 * @return * @throws Exception */
    public static String sendHttpRequest(String httpURL, Map<String, String> params) throws Exception { 
        //建立URL连接对象
        URL url = new URL(httpURL);
        //创建连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置请求的方式(需要是大写的)
        conn.setRequestMethod("POST");
        //设置需要输出
        conn.setDoOutput(true);
        //判断是否有参数.
        if (params != null && params.size() > 0) { 
            StringBuilder sb = new StringBuilder();
            for (Entry<String, String> entry : params.entrySet()) { 
                sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
            }
            //sb.substring(1)去除最前面的&
            conn.getOutputStream().write(sb.substring(1).toString().getBytes("utf-8"));
        }
        //发送请求到服务器
        conn.connect();
        //获取远程响应的内容.
        String responseContent = StreamUtils.copyToString(conn.getInputStream(), Charset.forName("utf-8"));
        conn.disconnect();
        return responseContent;
    }

    /** * 模拟浏览器的请求 * * @param httpURL 发送请求的地址 * @param jesssionId 会话Id * @return * @throws Exception */
    public static void sendHttpRequest(String httpURL, String jesssionId) throws Exception { 
        //建立URL连接对象
        URL url = new URL(httpURL);
        //创建连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置请求的方式(需要是大写的)
        conn.setRequestMethod("POST");
        //设置需要输出
        conn.setDoOutput(true);
        conn.addRequestProperty("Cookie", "JSESSIONID=" + jesssionId);
        //发送请求到服务器
        conn.connect();
        conn.getInputStream();
        conn.disconnect();
    }
}

测试代码

 @Test
    void contextLoads() throws Exception { 
        String url="https://way.jd.com/jisuapi/weather";
        Map<String,String> hashMap=new HashMap<>();
        hashMap.put("city","汕头");
        hashMap.put("appkey","");
        String s = HttpUtil.sendHttpRequest(url, hashMap);
        System.out.println(s);
    }

注意appkey的value值需要有参数,这里测试用的接口时京东万象的天气接口

    原文作者:木木在线撸码
    原文地址: https://blog.csdn.net/weixin_49861429/article/details/108615448
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章