spring boot使用RestTemplate进行post发

2019-02-21  本文已影响0人  善良的小布丁

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<String> 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;

}

}

上一篇下一篇

猜你喜欢

热点阅读