httpclient中的post请求

来源:互联网 发布:网络代理平台 编辑:程序博客网 时间:2024/06/05 03:21

工作中遇到了需要调用restful接口,本人是个小菜鸟,对怎么去调用别人接口没用过,百度挺多的,但是现成的东西,用完之后还是很容易忘记,这写的是我自己对httpclient调用的理解。(欢迎大神指正)

public static HashMap<String, String> post(CloseableHttpClient httpclient, String url,
                                               String json,String authorization)
            throws IOException {
        HashMap<String, String> resultMap = new HashMap<>();
        // 创建默认的httpClient实例.使用的org.apache.http中的包

   
        /*CloseableHttpClient httpclient = HttpClients.createDefault(); */
        // 创建httppost,创建一个请求,如postman中的要创建一个请求一样,创建请求时把地址作为参数。    
        HttpPost httppost = new HttpPost(url);

//设置请求头,postman中也是一样的,,需要什么请求头就设置什么。
        httppost.addHeader("Content-Type", "application/json");
        httppost.addHeader("Authorization", authorization);

//这步相当于是postman中的body,要设置请求参数类型,和内容。
        HttpEntity entity1 = null;
        // 创建参数队列 ,带编码格式是防止乱码,就因为这个出现的乱码   
        StringEntity se = new StringEntity(json,Charset.forName("utf-8"));

//设置参数队列的编码,和请求类型。
        se.setContentEncoding("UTF-8");
        se.setContentType("application/json");

//把参数队列设置到请求中
        httppost.setEntity(se);

//执行请求。并返回结果
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            entity1 = response.getEntity();
            if (entity1 != null) {
                String code = response.getStatusLine().getStatusCode() + "";
                resultMap.put("code", code);
                if ("200".equals(code)) {
                    resultMap.put("data", EntityUtils.toString(entity1, "UTF-8"));
                } else {
                    resultMap.put("data", null);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }

         

原创粉丝点击