spring boot使用RestTemplate进行post发送json数据请求其他服务器

1:在工程的Application中注册RestTemplate

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.annotation.Bean;

import org.springframework.web.client.RestTemplate;

@SpringBootApplication

public class SpringBootRequestApplication {

public static void main(String[] args) {

SpringApplication.run(SpringBootRequestApplication.class, args);

}

//注册RestTemplate

@Bean

public RestTemplate restTemplate(){

RestTemplate restTemplate=new RestTemplate();

return  restTemplate;

}

}


2:在 Controller中调用RestTemplate,调用方法如下:

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.client.RestTemplate;

import com.bio.bean.GetQuestionInfoResponse;

import com.bio.bean.Request;

import com.fasterxml.jackson.core.JsonParseException;

import com.fasterxml.jackson.databind.JsonMappingException;

import com.fasterxml.jackson.databind.ObjectMapper;

@RestController

@RequestMapping("/api/jsontest")

public class RequestController {

//引用RestTemplate

@Autowired

private RestTemplate restTemplate;

@RequestMapping("/request")

@ResponseBody

public String updatauser(@RequestBody Request request) {

//得到json数据

ResponseEntity responseEntity =restTemplate.postForEntity("你的post网址", request, String.class);

//返回json数据

return responseEntity ;

}

//得到的Json串可通过此方法转换成对象,不过需要在bean类里面添加无参的构造方法

public static Object jsonToObj(Object obj,String jsonStr)  {

ObjectMapper mapper = new ObjectMapper();

try {

return obj = mapper.readValue(jsonStr, obj.getClass());

} catch (JsonParseException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (JsonMappingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return mapper;

}

}


你可能感兴趣的:(spring boot使用RestTemplate进行post发送json数据请求其他服务器)