1. 程式人生 > >HttpClient通過Post方式傳送Json請求

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");
            }
        }