httpclient 簡單例項
阿新 • • 發佈:2018-12-27
使用httpclient執行get請求
@Test public void doGet() throws Exception { //建立一個httpclient物件 CloseableHttpClient httpClient = HttpClients.createDefault(); //建立一個GET物件 HttpGet get = new HttpGet("http://www.sogou.com"); //執行請求 CloseableHttpResponse response = httpClient.execute(get); //取響應的結果 int statusCode = response.getStatusLine().getStatusCode(); System.out.println(statusCode); HttpEntity entity = response.getEntity(); String string = EntityUtils.toString(entity, "utf-8"); System.out.println(string); //關閉httpclient response.close(); httpClient.close(); }
執行get請求帶引數
@Test public void doGetWithParam() throws Exception{ //建立一個httpclient物件 CloseableHttpClient httpClient = HttpClients.createDefault(); //建立一個uri物件 URIBuilder uriBuilder = new URIBuilder("http://www.sogou.com/web"); uriBuilder.addParameter("query", "花千骨"); HttpGet get = new HttpGet(uriBuilder.build()); //執行請求 CloseableHttpResponse response = httpClient.execute(get); //取響應的結果 int statusCode = response.getStatusLine().getStatusCode(); System.out.println(statusCode); HttpEntity entity = response.getEntity(); String string = EntityUtils.toString(entity, "utf-8"); System.out.println(string); //關閉httpclient response.close(); httpClient.close(); }