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; }
由于本人是自己学习总结出来的,有不足之处,请各位看官批评指出,我将及时改正,以提高知识总结的正确性和严谨性,为大家学习提供方便!!!
如若转载,请注明出处!!!