HttpClient通过Post方式发送Json请求

 json 对象转成string 。转换的很多

CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(CONNECT_TIME_OUT).setConnectionRequestTimeout(CONNECT_REQ_TIME_OUT)
                .setSocketTimeout(SOCKET_TIME_OUT).build();
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-type", "application/json; charset=utf-8");
        httpPost.setHeader("Accept", "application/json");
        // 传入的header参数
        if (null != headerParamsMap)
        {
            for (Map.Entry<String, String> entry : headerParamsMap.entrySet())
            {
                String key = entry.getKey();
                String value = entry.getValue();
                httpPost.setHeader(key, value);
            }
        }

        httpPost.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
        try
        {
            CloseableHttpResponse res = httpClient.execute(httpPost);
            result = EntityUtils.toString(res.getEntity());
            if (res.getStatusLine().getStatusCode() != 200 && res.getStatusLine().getStatusCode() != 201)
            {
                throw new RouteException(result, "SERVICE_POST_ERR");
            }
            res.close();
        }
        catch (IOException e)
        {
            String errorMsg = url + ":httpPostWithJSON connect faild";
            throwsRouteException(errorMsg, e, "POST_CONNECT_FAILD");
        }
        finally
        {
            try
            {
                httpClient.close();
            }
            catch (IOException e)
            {
                String errorMsg = url + ":close  httpClient faild";
                throwsRouteException(errorMsg, e, "CLOSE_CONNECT_FAILD");
            }
        }

猜你喜欢

转载自blog.csdn.net/zhuchunyan_aijia/article/details/81217482