Java 服務器端與服務器端的通信之httpclient

1、我們需要添加兩個第三方jar包
httpclient-4.5.2.jar
httpcore-4.4.4.jar
2、下面是部分示例代碼

public String getCurrentNum(){
        CloseableHttpClient httpclient  =   HttpClients.createDefault();
        try {
            String strURL                   = "訪問服務器的地址";
            HttpGet httpget                 =   new HttpGet(strURL);
            CloseableHttpResponse response  =   httpclient.execute(httpget);
            try {    
                HttpEntity entity   =   response.getEntity();  
                System.out.println("request url : " + strURL);
                if (entity != null) {
                    String strContent  = EntityUtils.toString(entity);
                    EntityUtils.consume(entity);
                    System.out.println("response content:" + strContent); 
                    return strContent;
                }  
            } finally {  
                response.close();  
            }
        }catch (Exception e) {
            e.printStackTrace(); 
        } finally {  
            // 關閉連接,釋放資源    
            try {  
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }
        return null;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章