一,概述
由于目前大部分项目都基于接口调用,jwt
安全机制以及分布式, 使得 HttpClient/RestTemplate
在项目中使用得非常之多, 接下来我将简单地介绍 HttpClient 4 API
的使用。不废话, 直接上码。
二,基本的 POST
用法
2.1 FORM
表单提交方式
基本的表单提交, 像注册,填写用户信息等 ... 都是一些基本的用法
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();
2.2 JSON
提交方式
JSON
的提交方式, 基本都是行业标准了。
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
用法
3.1 上传附件
由于上传附件方式 服务端基本上都是 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);
3.2 上传附件的同时传递 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
方法。