//post 请求  body传参数
private JSONObject post(String url, JSONObject params) {
        LogerConstant.screenLog.info("[screen] 请求 " + url + " 参数 " + params.toString());
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity httpEntity = new HttpEntity<>(params.toString(), headers);
        String body = restTemplate.postForObject(url, httpEntity, String.class);
        LogerConstant.screenLog.info("[screen] 返回" + body);
        JSONObject json = JSONObject.parseObject(body);
        if (0 != json.getIntValue("code")) {
            return null;
        }
        return json;
    }

//get 请求 传参数
    private JSONObject get(String url, MultiValueMap<String, Object> params) {
        LogerConstant.screenLog.info("[screen] 请求 " + url + " 参数 " + params.toString());
        String body = new RestTemplate().getForObject(url, String.class, params);
        JSONObject json = JSONObject.parseObject(body);
        LogerConstant.screenLog.info("[screen] 返回" + body);
        if (0 != json.getIntValue("code")) {
            return null;
        }
        return json;
    }

//post body传json, header传参数
    private JSONObject postBody(String url, String token, JSONArray jsonArray) {
        LogerConstant.screenLog.info("[screen] 请求 " + url + " 参数 token:" + token + " json:" + jsonArray.toString());
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        httpHeaders.add("token", token);
        HttpEntity<String> httpEntity = new HttpEntity<>(jsonArray.toString(), httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        String body = restTemplate.postForEntity(url, httpEntity, String.class).getBody();
        JSONObject object = JSONObject.parseObject(body);
        LogerConstant.screenLog.info("[screen] 返回" + body);
        return object;
    }
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐