SpringBoot使用HttpClient遠程調用


一.  Get請求

try {
            //拼接url
            url = url+"access_token="+token+"&department_id=1&fetch_child=1";
            //解決證書明匹配問題
            SSLSocketFactory.getSocketFactory().setHostnameVerifier(new     
                    AllowAllHostnameVerifier());
            //根據地址獲取請求
            HttpGet request = new HttpGet(url);
            //獲取當前客戶端對象
            HttpClient httpClient = new DefaultHttpClient();
            //通過請求獲取相應對象
            HttpResponse response = httpClient.execute(request);
            // 判斷網絡連接狀態碼是否正常(0--200都數正常)
            String result=null;
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result= EntityUtils.toString(response.getEntity(),"utf-8");
            }    

} catch (Exception e) {
       e.printStackTrace();
 }                           

 

二.  Post請求

 try{
        String url = userMapper.getValue(urlId);
        url = url + "access_token=" + token;
        //主機證書明不匹配問題
        SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());

     //獲取請求地址 HttpPost post
= new HttpPost(url);
     //獲取當前客戶端對象 HttpClient httpClient
= new DefaultHttpClient(); // 設置超時時間 httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000);      //設置參數 StringEntity s = new StringEntity(jsonObject.toString()); s.setContentEncoding("UTF-8"); s.setContentType("application/json"); post.setEntity(s);      //通過請求獲得相應的對象    HttpResponse res = client.execute(post);
     //判斷是否成功
     if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
    HttpEntity entity = res.getEntity();
    String result = EntityUtils.toString(res.getEntity());// 返回json格式:
    }
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM