Java中调用第三方接口的简单方法post和get请求
//这是springboot下写的,采用注解@Component注入的post请求 //写出对应的实体类进行结果的接收 public class PointDto { private String PointText; @Component public class url { //连接统一管理,一般放在application-dev.yml下面通过下面的方法获取 @Value("${gateway.getKnowledgePoint}") private String Url; //RestTemplate 第三方接口运用这个方法进行调用 public String Point(String questionText) { RestTemplate restTemplate = new RestTemplate(); String url = getKnowledgePointUrl; String knowledge = restTemplate.postForObject(url, questionText, String.class); return knowledge; }
get请求
同样对应实体类的接收
public class PointDto { private String PointText;
@Component public class QuestionByIdUtils { @Value("${gateway.getQuestionById}") private String getQuestionByIdUrl; public String qusetionById(Integer questionId) { RestTemplate restTemplate1 = new RestTemplate(); String url = getQuestionByIdUrl; String strs = url + questionId; //IdDto.class对应的实体类 IdDto IdDto = restTemplate1.getForObject(strs, IdDto.class); //对结果进行获取 Map<String,Object> data1 = (Map<String,Object>)IdDto.getData(); return (String) data1.get("Title"); } }
//get public class QuestionTypeUtil { @Value("${gateway.getType}") private String getTypeUrl; public String qusetionTypes(String Text){ //第三方题型接口 RestTemplate restTemplate1 = new RestTemplate(); String url = getTypeUrl; String strs = url + Text; // 对str类型的转化,因为报异常 UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(strs); UriComponents uriComponents = builder.build(); //获取连接对象 QuestionTypeDto questionTypeDto = restTemplate1.getForObject(uriComponents.toUri(), TypeDto.class ); //结果的获取 List<List<String>> classes = TypeDto.getClasses(); List<String> s = classes.get(0); String s1 = s.get(0); return s1; } }
#post请求两个参数
@Component public class QuestionsTextUtils { public Map<String, Object> qusetionByMes(List<Map<String,String>> questionText, Integer num) { HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8"); headers.setContentType(type); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); HttpEntity<List<Map<String,String>>> mapHttpEntity = new HttpEntity<>(questionText, headers); RestTemplate restTemplate1 = new RestTemplate(); String url = "http://testaliyun.eebbk.net/social-search/test/search/text?subject="; String strs = url + num; // String s = restTemplate1.postForObject(strs, mapHttpEntity, String.class); Map<String, Object> s = restTemplate1.postForObject(strs, mapHttpEntity, Map.class); return s ; }
.控制层
//@RequestBod 返回集合必须加这个注解 @PostMapping("/getQuestionIds") @ApiOperation(value = "", notes = "") public ResponseBean<Map<String, Object>> findAllData(@RequestBody List<Map<String,String>> questionText, Integer num) { try { return new ResponseBean(questionsTextUtils.qusetionByMes(questionText, num)); }catch (Exception e){ log.error("获取试题id失败"); e.printStackTrace(); } return new ResponseBean<>(); }
上一篇:
通过多线程提高代码的执行效率例子