HttpClient 使用指南 - POST篇

一,概述

因爲目前大部分項目都基於接口調用,jwt安全機制以及分佈式, 使得 HttpClient/RestTemplate 在項目中使用得很是之多, 接下來我將簡單地介紹 HttpClient 4 API 的使用。不廢話, 直接上碼。java


二,基本的 POST 用法

2.1 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();

2.2 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用法

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 方法。app

相關文章
相關標籤/搜索