//接口全路径:http://localhost:18081/hp @PostMapping("hp") public String hp(){ return "ss"; }
@Test public void testHttpPost(){ try { //1.构建http对象(相当于浏览器) CloseableHttpClient httpClient = HttpClients.createDefault(); //3.创建http post请求对象 HttpPost post = new HttpPost("http://localhost:18081/hp"); //4.创建响应对象 CloseableHttpResponse response = httpClient.execute(post); /** * 由于响应接口返回的是一个字符串,因此需要转换 * 响应体数据封装在HttpEntity对象中 */ String s = EntityUtils.toString(response.getEntity(), "utf-8"); System.out.println(s); //5.释放资源 response.close(); httpClient.close(); } catch (Exception e) { e.printStackTrace(); } }
响应结果:
23:21:00.390 [main] DEBUG org.apache.http.impl.conn.DefaultManagedHttpClientConnection - http-outgoing-0: set socket timeout to 0 23:21:00.390 [main] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection released: [id: 0][route: {}->http://localhost:18081][total kept alive: 1; route allocated: 1 of 2; total allocated: 1 of 20] ss 23:21:00.390 [main] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection manager is shutting down 23:21:00.390 [main] DEBUG org.apache.http.impl.conn.DefaultManagedHttpClientConnection - http-outgoing-0: Close connection
@Test public void testHttpPost(){ try { //1.构建http对象(相当于浏览器) CloseableHttpClient httpClient = HttpClients.createDefault(); //3.创建http post请求对象 HttpPost post = new HttpPost("http://localhost:18081/hp"); /** * 3.1添加请求参数,post请求参数是在body中 * NameValuePair:封装参数的接口 * BasicNameValuePair: 接口实现类 */ List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("key","wjh")); /** * 创建httpentity接口的文本实现类对象 * 封装参数并设置编码 */ HttpEntity httpEntity = new UrlEncodedFormEntity(params,"utf-8"); post.setEntity(httpEntity);//设置参数体 //4.创建响应对象 CloseableHttpResponse response = httpClient.execute(post); /** * 由于响应接口返回的是一个字符串,因此需要转换 * 响应体数据封装在HttpEntity对象中 */ String s = EntityUtils.toString(response.getEntity(), "utf-8"); System.out.println(s); //5.释放资源 response.close(); httpClient.close(); } catch (Exception e) { e.printStackTrace(); } }
响应接口:
//接口全路径:http://localhost:18081/hp @PostMapping("hp") public String hp(String key){ return "ss" + key; }
post请求结果:
23:29:18.230 [main] DEBUG org.apache.http.impl.conn.DefaultManagedHttpClientConnection - http-outgoing-0: set socket timeout to 0 23:29:18.230 [main] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection released: [id: 0][route: {}->http://localhost:18081][total kept alive: 1; route allocated: 1 of 2; total allocated: 1 of 20] sswjh 23:29:18.230 [main] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection manager is shutting down 23:29:18.230 [main] DEBUG org.apache.http.impl.conn.DefaultManagedHttpClientConnection - http-outgoing-0: Close connection