所需maven jar包
org.apache.httpcomponents httpclient 4.4.1 org.apache.httpcomponents httpcore 4.4.1
发出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,模拟一个表单 Listlist = new ArrayList (); 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());