Java post 请求封装, 代码粘贴即可使用

Java post 请求封装, 代码粘贴即可使用

/**
 * 发送POST请求
 * obj为请求体,可为空
 * headers为请求头,可为空
 */
public String sendPost(String url, JSONObject obj, Map headers) {
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;
    String result = "";
    //创建post请求对象
    HttpPost post = new HttpPost(url);
    //遍历请求头,挨个插入请求
    if(headers != null){
        for(String key : headers.keySet()){
            post.addHeader(key, headers.get(key));
        }
    }
    try {
        if(obj != null){
            StringEntity jsonStr = new StringEntity(obj.toJSONString(), Charset.forName("UTF-8"));
            post.setEntity(jsonStr);
        }
        httpClient = HttpClients.createDefault();
        //启动执行请求,并获得返回值
        response = httpClient.execute(post);
        //得到返回的entity对象
        HttpEntity entity = response.getEntity();
        //把实体对象转换为string
        result = EntityUtils.toString(entity, "UTF-8");
        //返回内容
    } catch (Exception e1) {
        e1.printStackTrace();
    } finally {
        // 关闭资源
        if (null != response) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != httpClient) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}

你可能感兴趣的:(java,开发语言,http)