所需maven jar包
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.4.1</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.1</version> </dependency>
發出get請求,可調用外部rest接口:
@org.junit.Test public void testGet() throws IOException, Exception { //創建HttpClient客戶端 CloseableHttpClient httpClient = HttpClients.createDefault(); //創建請求方式 post get http://localhost:8888/demo/test/ String uri = "http://localhost:8888/demo/test/hello/cc/a"; HttpGet httpGet = new HttpGet(uri); CloseableHttpResponse response = httpClient.execute(httpGet); //相應結果 int statusCode = response.getStatusLine().getStatusCode(); System.out.println(statusCode); HttpEntity entity = response.getEntity(); String string = EntityUtils.toString(entity); System.out.println(string); response.close(); httpClient.close(); }
發出post請求,模擬表單發請求:
@org.junit.Test public void testPost() throws IOException, Exception { //創建HttpClient客戶端 CloseableHttpClient httpClient = HttpClients.createDefault(); //創建請求方式 post get String uri = "http://localhost:8888/demo/test/testPost"; HttpPost httpPost = new HttpPost(uri); //創建一個Entity,模擬一個表單 List<NameValuePair> list = new ArrayList<NameValuePair>(); list.add(new BasicNameValuePair("id", "1001")); list.add(new BasicNameValuePair("name", "小黑")); //把表單包裝成一個HttpEntity對象 HttpEntity stringEntity = new UrlEncodedFormEntity(list,"utf-8"); //設置請求的內容 httpPost.setEntity(stringEntity); CloseableHttpResponse response = httpClient.execute(httpPost); //相應結果 int statusCode = response.getStatusLine().getStatusCode(); System.out.println(statusCode); HttpEntity entity = response.getEntity(); String string = EntityUtils.toString(entity); System.out.println(string); response.close(); httpClient.close(); }
get請求添加其他參數,可參照:
//創建一個uri對象 URIBuilder uriBuilder = new URIBuilder("http://www.sogou.com/web"); uriBuilder.addParameter("query","花千骨"); HttpGet get = new HttpGet(uriBuilder.build());