工具类
package org.springblade.common.utils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpClientUtils {
public static String sendGetRequest(String url, Map<String, String> parameters) throws URISyntaxException, IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
URIBuilder uriBuilder = new URIBuilder(url);
for (Map.Entry<String, String> entry : parameters.entrySet()) {
uriBuilder.addParameter(entry.getKey(), entry.getValue());
}
URI uri = uriBuilder.build();
HttpGet httpGet = new HttpGet(uri);
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
httpClient.close();
return result;
}
public static String sendPostRequest(String url, Map<String, String> parameters) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> params = new ArrayList<>();
for (Map.Entry<String, String> entry : parameters.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
httpClient.close();
return result;
}
}
发送 GET 请求的示例代码如下
try {
String url = "http://api.example.com/getData";
Map<String, String> parameters = new HashMap<>();
parameters.put("param1", "value1");
parameters.put("param2", "value2");
String response = HttpClientUtils.sendGetRequest(url, parameters);
System.out.println(response);
} catch (Exception e) {
e.printStackTrace();
}
发送 POST 请求的示例代码如下
try {
String url = "http://api.example.com/submitData";
Map<String, String> parameters = new HashMap<>();
parameters.put("param1", "value1");
parameters.put("param2", "value2");
String response = HttpClientUtils.sendPostRequest(url, parameters);
System.out.println(response);
} catch (Exception e) {
e.printStackTrace();
}