spring boot RestTemplate post 參數json返回json

定義config

@Configuration
public class ApiConfig {
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);//ms
        factory.setConnectTimeout(5000);//ms
        return factory;
    }
}

controller

@RestController
@RequestMapping("test")
public class TestController {
    private static final Logger log = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/getProgress")
    public void getProgress() throws IOException {
        String url = "http://192.168.0.109:6567/seaguard/game/reqProgress";
        //正確json體
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());

        for (int i = 0; i < 10000; ++i) {
            String openid = "openid_" + i;
            JSONObject postData = new JSONObject();
            postData.put("openid", openid);
            postData.put("type", 0);
            postData.put("detail", "{asdasd}");
            //todo http postforentity
            JSONObject json = restTemplate.postForEntity(url, postData, JSONObject.class).getBody();
            log.info("json:{}", json);
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章