httppost 请求

public String httpPost(String url, String params,Map<String, String> header) throws IOException {
    String responseBody = "";
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        StringEntity entity = new StringEntity(params, "UTF-8");
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);
        if(header != null){
            for(Map.Entry<String, String> entry : header.entrySet()){
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }
        ResponseHandler<String> responseHandler = response -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity resEntity = response.getEntity();
                try {
                    return resEntity != null ? EntityUtils.toString(resEntity) : null;
                } catch (ParseException ex) {
                    throw new ClientProtocolException(ex);
                }
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        };
        responseBody = httpclient.execute(httpPost, responseHandler);
    }
    return responseBody;
}

猜你喜欢

转载自blog.csdn.net/wsgytwsgyt/article/details/83346421