因为目前大部分项目都基于接口调用,jwt
安全机制以及分布式, 使得 HttpClient/RestTemplate
在项目中使用得很是之多, 接下来我将简单地介绍 HttpClient 4 API
的使用。不废话, 直接上码。java
POST
用法FORM
表单提交方式基本的表单提交, 像注册,填写用户信息等 ... 都是一些基本的用法json
CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://api.example.com/"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("username", "Adam_DENG")); params.add(new BasicNameValuePair("password", "password")); httpPost.setEntity(new UrlEncodedFormEntity(params)); CloseableHttpResponse response = client.execute(httpPost); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); client.close();
JSON
提交方式JSON
的提交方式, 基本都是行业标准了。api
RequestModel model = new RequestModel(); model.setRealname("Adam_DENG"); model.setPassword("password"); CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(targetUrl); // 这里使用了对象转为json string String json = JSON.toJSONString(model); StringEntity entity = new StringEntity(json, "UTF-8"); // NOTE:防止中文乱码 entity.setContentType("application/json"); httpPost.setEntity(entity); httpPost.setHeader("Accept", "application/json; charset=UTF-8"); httpPost.setHeader("Content-type", "application/json; charset=UTF-8"); CloseableHttpResponse response = client.execute(httpPost); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); client.close();
POST
用法因为上传附件方式 服务端基本上都是 MultipartFile
模式。 因此客户端也是相对于的 MultipartEntityBuilder
。安全
CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(targetUrl); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // 这里支持 `File`, 和 `InputStream` 格式, 对你来讲哪一个方便, 使用哪一个。 // 由于个人文件是从 `URL` 拿的,因此代码以下, 其余形式相似 InputStream is = new URL("http://api.demo.com/file/test.txt").openStream(); builder.addBinaryBody("file", is, ContentType.APPLICATION_OCTET_STREAM, "test.txt"); HttpEntity entity = builder.build(); httpPost.setEntity(entity); CloseableHttpResponse response = client.execute(httpPost);
Url
参数CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(targetUrl); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); InputStream is = new URL("http://api.demo.com/file/test.txt").openStream(); builder.addBinaryBody("file", is, ContentType.APPLICATION_OCTET_STREAM, "test.txt"); StringBody realnameBody = new StringBody("Adam_DENG", ContentType.create("text/plain", Charset.forName("UTF-8"))); builder.addPart("realname", realnameBody); HttpEntity entity = builder.build(); httpPost.setEntity(entity); CloseableHttpResponse response = client.execute(httpPost);
这个教程中我只是介绍了咱们平时在项目中使用最多的几个 HttpClient API
方法。app