HttpClient的几种请求方式

 

 

 

public static String doPostToken(String tokenUrl,String clientId,String clientSecret,String grantType) {
        
        CloseableHttpResponse response = null;
        String resultToken = "";
        try {
            //1.创建Httpclient对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            
            //2.创建Http Post请求
            HttpPost httpPost = new HttpPost(tokenUrl);
            
            //3.封装请求参数
            List<BasicNameValuePair> list = new ArrayList<>();
            list.add(new BasicNameValuePair("client_id", clientId));
            list.add(new BasicNameValuePair("client_secret", clientSecret));
            list.add(new BasicNameValuePair("grant_type", grantType));
            httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
        
            //4.执行http请求
            response = httpClient.execute(httpPost);
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK ){
                
                JSONObject jsonObject = JSONObject.fromObject(EntityUtils.toString(response.getEntity(), "utf-8"));
                resultToken = (String) Optional.ofNullable(jsonObject.get("access_token")).orElseGet(String::new);
            }else{
                resultToken = "";
            }
        } catch (Exception e) {
            LOG.error("post request get Token ERR XXXXXXXXXXXXXXXXX"+e);
        }finally {
            try {
                response.close();
            } catch (IOException e) {
                LOG.error("post request get Token close ERR XXXXXXXXXXXXXXXXX"+e);
            }
        }
        return resultToken;
    }

 

posted @ 2019-10-09 15:24  硝烟漫过十八岁  阅读(791)  评论(0编辑  收藏  举报