接口自调 sendGetRequest、sendPostRequest、sendPutRequest和sendDeleteRequest,分别用于发送GET、POST、PUT和DELETE请求。 这些方法都接受两个参数:endpoint表示要访问的API端点路径,requestBody表示可选的请求体数据。这些方法在内部使用Apache HttpClient来发送请求,并返回响应的字符串表示形式。
相关代码如下
private final String BASE_URL = “http://127.0.0.1:8082”; // 基础URL,根据实际情况修改
public String sendGetRequest(String endpoint, Map<String,String> params) throws IOException, URISyntaxException {
CloseableHttpClient httpClient = HttpClients.createDefault();
URIBuilder uriBuilder = new URIBuilder(BASE_URL + endpoint);
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
uriBuilder.addParameter(entry.getKey(), entry.getValue());
}
}
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader("//这里封装具体的header,无需要可不封装");
HttpResponse response = httpClient.execute(httpGet);
return extractResponseString(response);
}
public String sendPostRequest(String endpoint, String requestBody) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(BASE_URL + endpoint);
setRequestBody(httpPost, requestBody);
httpPost.setHeader("//这里封装具体的header,无需要可不封装");
HttpResponse response = httpClient.execute(httpPost);
return extractResponseString(response);
}
public String sendPutRequest(String endpoint, String requestBody) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(BASE_URL + endpoint);
httpPut.setHeader("//这里封装具体的header,无需要可不封装");
setRequestBody(httpPut, requestBody);
HttpResponse response = httpClient.execute(httpPut);
return extractResponseString(response);
}
public String sendDeleteRequest(String endpoint,Map<String,String> params) throws IOException, URISyntaxException {
CloseableHttpClient httpClient = HttpClients.createDefault();
URIBuilder uriBuilder = new URIBuilder(BASE_URL + endpoint);
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
uriBuilder.addParameter(entry.getKey(), entry.getValue());
}
}
HttpDelete httpDelete = new HttpDelete(BASE_URL + endpoint);
httpDelete.setHeader("//这里封装具体的header,无需要可不封装");
HttpResponse response = httpClient.execute(httpDelete);
return extractResponseString(response);
}
private void setRequestBody(HttpEntityEnclosingRequestBase request, String requestBody) {
if (requestBody != null) {
StringEntity entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
request.setEntity(entity);
}
}
private String extractResponseString(HttpResponse response) throws IOException {
HttpEntity responseEntity = response.getEntity();
return EntityUtils.toString(responseEntity);
}
以上仅个人学习使用,有问题也希望指出