post请求方式 - 使用restTemplate而不使用httpClient,headers.setContentType(MediaType.APPLICATION_JSON_UTF8)

public static String doPostForJson(String url, String json,String byteAuthorization) {
        RestTemplate restTemplate = new RestTemplate();

        logger.info("restTemplate invoke post method. url:[{}], json:[{}]", url, json);
        long startTime = System.currentTimeMillis();
        String result = "";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("Byte-Authorization",byteAuthorization);

        HttpEntity<String> request = new HttpEntity<>(json, headers);
        result = restTemplate.postForEntity(url,request,String.class).getBody();


        logger.info("restTemplate invoke [{}] consume time is,[{}] ms.", url, System.currentTimeMillis() - startTime);
        logger.info("restTemplate invoke post method. result:[{}]", result);
        return result;
    }


    /**
     * 通过该方式,对方未正确接收到参数
     * https://blog.csdn.net/zy_281870667/article/details/87723177
     * @param url
     * @param json
     * @param byteAuthorization
     * @return
     */
    public static String doPostForJsonOld(String url, String json,String byteAuthorization) {
        logger.info("invoke post method. url:[{}], json:[{}]", url, json);
        long startTime = System.currentTimeMillis();
        String result = "";
        HttpClient httpClient = wrapClient(url);

        StringEntity se = new StringEntity(json, "UTF-8");
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
//        se.setContentType(new BasicHeader("Accept", "application/json"));
        /**
         * 数据格式
         * Byte-Authorization: SHA256-RSA2048 appid="ttxxx",nonce_str="DC10180A100073E70A48F195DA2AF2E6",timestamp="1623934869",key_version="1",signature=""'
         */
        se.setContentType(new BasicHeader("Byte-Authorization", byteAuthorization));
        se.setContentEncoding("UTF-8");

        // 创建HttpPost
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(se);
        // 执行POST请求
        try {
            HttpResponse response = httpClient.execute(httpPost);
            // 若状态码为200 ok
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 取出回应字串
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            logger.error("Calling douyin payment interface is abnormal >>> url:[{}], json:[{}]",
                    url, json, e);
        }

        logger.info("invoke [{}] consume time is,[{}] ms.", url, System.currentTimeMillis() - startTime);
        logger.info("invoke post method. result:[{}]", result);
        return result;
    }

 

posted on 2023-06-05 22:05  oktokeep  阅读(177)  评论(0编辑  收藏  举报