大多數Java應用程序都會經過HTTP協議來調用接口訪問各類網絡資源,JDK也提供了相應的HTTP工具包,可是使用起來不夠方便靈活,因此咱們能夠利用Apache的HttpClient來封裝一個具備訪問HTTP協議基本功能的高效工具類,爲後續開發使用提供方便。html
文章要點:java
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.5</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.11</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency>
HttpClient client = HttpClientBuilder.create().build();
GET請求使用HttpGet,POST請求使用HttpPost,並傳入請求的URLgit
// POST請求 HttpPost post = new HttpPost(url); // GET請求,URL中帶請求參數 HttpGet get = new HttpGet(url);
List<NameValuePair> list = new ArrayList<>(); list.add(new BasicNameValuePair("username", "admin")); list.add(new BasicNameValuePair("password", "123456")); // GET請求方式 // 因爲GET請求的參數是拼裝在URL後方,因此須要構建一個完整的URL,再建立HttpGet實例 URIBuilder uriBuilder = new URIBuilder("http://www.baidu.com"); uriBuilder.setParameters(list); HttpGet get = new HttpGet(uriBuilder.build()); // POST請求方式 post.setEntity(new UrlEncodedFormEntity(list, Charsets.UTF_8));
Map<String,String> map = new HashMap<>(); map.put("username", "admin"); map.put("password", "123456"); Gson gson = new Gson(); String json = gson.toJson(map, new TypeToken<Map<String, String>>() {}.getType()); post.setEntity(new StringEntity(json, Charsets.UTF_8)); post.addHeader("Content-Type", "application/json");
調用HttpClient實例的execute方法發送請求,返回一個HttpResponse對象github
HttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
post.releaseConnection();
HttpClient工具類代碼(根據相應使用場景進行封裝):apache
public class HttpClientUtil { // 發送GET請求 public static String getRequest(String path, List<NameValuePair> parametersBody) throws RestApiException, URISyntaxException { URIBuilder uriBuilder = new URIBuilder(path); uriBuilder.setParameters(parametersBody); HttpGet get = new HttpGet(uriBuilder.build()); HttpClient client = HttpClientBuilder.create().build(); try { HttpResponse response = client.execute(get); int code = response.getStatusLine().getStatusCode(); if (code >= 400) throw new RuntimeException((new StringBuilder()).append("Could not access protected resource. Server returned http code: ").append(code).toString()); return EntityUtils.toString(response.getEntity()); } catch (ClientProtocolException e) { throw new RestApiException("postRequest -- Client protocol exception!", e); } catch (IOException e) { throw new RestApiException("postRequest -- IO error!", e); } finally { get.releaseConnection(); } } // 發送POST請求(普通表單形式) public static String postForm(String path, List<NameValuePair> parametersBody) throws RestApiException { HttpEntity entity = new UrlEncodedFormEntity(parametersBody, Charsets.UTF_8); return postRequest(path, "application/x-www-form-urlencoded", entity); } // 發送POST請求(JSON形式) public static String postJSON(String path, String json) throws RestApiException { StringEntity entity = new StringEntity(json, Charsets.UTF_8); return postRequest(path, "application/json", entity); } // 發送POST請求 public static String postRequest(String path, String mediaType, HttpEntity entity) throws RestApiException { logger.debug("[postRequest] resourceUrl: {}", path); HttpPost post = new HttpPost(path); post.addHeader("Content-Type", mediaType); post.addHeader("Accept", "application/json"); post.setEntity(entity); try { HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(post); int code = response.getStatusLine().getStatusCode(); if (code >= 400) throw new RestApiException(EntityUtils.toString(response.getEntity())); return EntityUtils.toString(response.getEntity()); } catch (ClientProtocolException e) { throw new RestApiException("postRequest -- Client protocol exception!", e); } catch (IOException e) { throw new RestApiException("postRequest -- IO error!", e); } finally { post.releaseConnection(); } } }
List<NameValuePair> parametersBody = new ArrayList(); parametersBody.add(new BasicNameValuePair("userId", "admin")); String result = HttpClientUtil.getRequest("http://www.test.com/user",parametersBody);
List<NameValuePair> parametersBody = new ArrayList(); parametersBody.add(new BasicNameValuePair("username", "admin")); parametersBody.add(new BasicNameValuePair("password", "123456")); String result = HttpClientUtil.postForm("http://www.test.com/login",parametersBody);
Map<String,String> map = new HashMap<>(); map.put("username", "admin"); map.put("password", "123456"); Gson gson = new Gson(); String json = gson.toJson(map, new TypeToken<Map<String, String>>() {}.getType()); String result = HttpClientUtil.postJSON("http://www.test.com/login", json);
關於HttpClient的詳細介紹看這裏:HttpClient入門json
本文爲做者kMacro原創,轉載請註明來源:https://zkhdev.github.io/2018/10/12/java_dev5/。網絡