JAVA使用Apache HttpClient实现PATCH请求的调用
1、Postman请求示例
-
Header:包含鉴权签名,此处省略系统内部签名获取方式
-
Body:包含nonce、timestamp、username等参数
-
Postman返回结果
2、代码实现
使用 Apache HttpClient工具类,来实现PATCH请求的接口调用,以下是代码实现,部分接口地址及参数因涉及隐私问题,已做处理。
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
/**
* @author zyq
* @description PATCH调用请求
* @create 2024-03-26 10:52
*/
public class IdmeshPatchRequest {
public static void main(String[] args) {
//编辑用户-测试-PATCH
try {
//定义请求参数body
JSONObject jsonObject = new JSONObject();
jsonObject.put("nonce", "2633gxnfzifkcby2fpmd");
jsonObject.put("timestamp", "1711438136734");
jsonObject.put("username", "zhangsf");
jsonObject.put("display_name", "xxx");
jsonObject.put("firstname", "xx");
jsonObject.put("lastname", "x");
jsonObject.put("realname", "");
jsonObject.put("pinyin", "zhangsanfeng");
jsonObject.put("mobile", "18866669999");
jsonObject.put("gender", "1");
System.out.println(jsonObject);
//创建一个可关闭的 HTTP 客户端实例 httpClient
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建一个 HTTP PATCH 请求实例,并指定目标资源的 URL
HttpPatch httpPatch = new HttpPatch("https://xxx.xxx.xxx/api/v1/users/174xxxxxxxx480");
//创建一个字符串实体,包含请求体内容和 UTF-8 字符编码
StringEntity entity = new StringEntity(jsonObject.toString(), StandardCharsets.UTF_8);
//将字符串实体设置到 HTTP PATCH 请求中
httpPatch.setEntity(entity);
//设置 HTTP 请求头,指定请求体内容类型为 JSON
httpPatch.setHeader("Content-Type", "application/json");
//设置签名
httpPatch.setHeader("X-Idmesh-Signature", "Xdxxxxxxxxxxxxxp7jG$sm3$8ae96xxxxxxxxxxxxxxxxxxxxxx82edc956547d508131eaxxxxxxxxxxxxxxxxxxxxfe8eaf");
//执行 HTTP PATCH 请求并获取响应
HttpResponse response = httpClient.execute(httpPatch);
//获取响应中的实体内容
HttpEntity responseEntity = response.getEntity();
// 创建一个 BufferedReader 对象,用于按行读取响应内容,并指定使用 UTF-8 字符编码解析内容
BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent(), StandardCharsets.UTF_8));
StringBuilder responseBody = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
responseBody.append(line);
}
System.out.println(responseBody.toString());
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}