httpClient远程调用

一、get请求 @Test public void testHttpGet() throws Exception { //第一步:把HttpClient使用的jar包添加到工程中。 //第二步:建立一个HttpClient的测试类 //第三步:建立测试方法。 //第四步:建立一个HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); //第五步:建立一个HttpGet对象,须要制定一个请求的url HttpGet get = new HttpGet("http://localhost:9000/mq/send?notifyURL=&businessType=1"); //第六步:执行请求。 CloseableHttpResponse response = httpClient.execute(get); //第七步:接收返回结果。HttpEntity对象。 HttpEntity entity = response.getEntity(); //第八步:取响应的内容。 String html = EntityUtils.toString(entity); log.info(html); //第九步:关闭response、HttpClient。 response.close(); httpClient.close(); }html


二、post请求 @Test public void testHttpPost() throws Exception { // 第一步:建立一个httpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 第二步:建立一个HttpPost对象。须要指定一个url HttpPost post = new HttpPost("http://localhost:9000/mq/send"); // 第三步:建立一个list模拟表单,list中每一个元素是一个NameValuePair对象 List<NameValuePair> formList = new ArrayList<>(); formList.add(new BasicNameValuePair("notifyURL", "111gege")); formList.add(new BasicNameValuePair("businessType", "1243")); // 第四步:须要把表单包装到Entity对象中。StringEntity StringEntity entity = new UrlEncodedFormEntity(formList, "utf-8"); post.setEntity(entity); // 第五步:执行请求。 CloseableHttpResponse response = httpClient.execute(post); // 第六步:接收返回结果 HttpEntity httpEntity = response.getEntity(); String result = EntityUtils.toString(httpEntity); System.out.println(result); log.info(result); // 第七步:关闭流。 response.close(); httpClient.close(); }post

相关文章
相关标签/搜索