Java Post JSON客戶端是一種用于向服務(wù)器發(fā)送POST請求并傳送JSON數(shù)據(jù)的工具。其中,POST請求是HTTP中一種常用的請求方式,可用于向服務(wù)器提交數(shù)據(jù),而JSON是一種輕量級的數(shù)據(jù)交換格式。
下面介紹如何使用Java Post JSON客戶端。
1. 添加依賴
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
2. 發(fā)送POST請求
//請求地址
String url = "http://www.example.com/api";
//參數(shù)
Map<String,Object> paramMap = new HashMap<>();
paramMap.put("username", "張三");
paramMap.put("age", 18);
//將參數(shù)轉(zhuǎn)為JSON
String jsonParam = JSON.toJSONString(paramMap);
//創(chuàng)建HttpClient
CloseableHttpClient httpClient = HttpClients.createDefault();
//創(chuàng)建Post請求
HttpPost httpPost = new HttpPost(url);
//設(shè)置請求頭
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
//設(shè)置請求體
StringEntity stringEntity = new StringEntity(jsonParam, "UTF-8");
httpPost.setEntity(stringEntity);
//發(fā)送請求
CloseableHttpResponse response = httpClient.execute(httpPost);
//獲取響應(yīng)結(jié)果
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
以上就是Java Post JSON客戶端的使用方法。