在springboot中使用jdbcTemplate(4)和okhttp3

想封装一个调用远程http接口的工具类。

第一个想到的就是Springboot中的RestTemplate,写了一个get请求,很容易就成功了。

但是写post请求的时候,无论怎么搞,都拿不到请求值。不得已换成了okHttp,很快就成功了。

把代码贴在这里,做一个记录。

统一了GET、POST请求的格式,都是传入URL地址和map类型的参数。

@Service
public class RemoteApiHandler {

    @Autowired
    private RestTemplate restTemplate;

    public String doGet(String url, Map<String, Object> params) {

        return restTemplate.getForObject(url, String.class, params);

    }


    public String doPost(String url, Map<String, Object> params) throws IOException {
        JSONObject jsonObject = new JSONObject(params);
        String content = jsonObject.toJSONString();
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, content);
        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }
}

 

posted @ 2022-07-26 10:15  Mars.wang  阅读(138)  评论(0编辑  收藏  举报