调用post方法
public static String doPostWeChat(String accessToken, String url, String tradeCode) throws Exception {// 创建一个默认的 HTTP 客户端实例CloseableHttpClient client = HttpClients.createDefault();CloseableHttpResponse response = null; // 响应对象初始化为空String context = StringUtils.EMPTY; // 初始化返回内容为空字符串HttpPost method = new HttpPost(url); // 创建 HTTP POST 请求对象,指定请求的 URLtry {// 配置请求超时时间RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000) // 读取数据超时时间(20秒).setConnectTimeout(40000) // 连接超时时间(40秒).setConnectionRequestTimeout(20000) // 从连接池获取连接的超时时间(20秒).build();method.setConfig(requestConfig); // 将配置应用到请求对象method.addHeader("Authorization", accessToken); // 添加授权头部method.addHeader("company", tradeCode); // 添加公司代码头部log.info(String.format("%s-----%s", "", "accessToken="+accessToken + "准备数据请求")); // 记录日志,表明请求准备发送response = client.execute(method); // 发送请求并获取响应log.info(String.format("%s-----%s", "", "accessToken="+accessToken + "请求已发送")); // 记录日志,表明请求已发送HttpEntity resEntity = response.getEntity(); // 获取响应实体context = EntityUtils.toString(resEntity, "UTF-8"); // 将响应实体转换为字符串(UTF-8 编码)} catch (Exception e) {throw e; // 抛出异常,供调用者处理} finally {if (response != null) {try {EntityUtils.consume(response.getEntity()); // 确保响应实体被完全消费response.close(); // 关闭响应对象method.abort(); // 中止请求client.close(); // 关闭 HTTP 客户端} catch (IOException e) {// 在此可以添加日志记录或其他处理逻辑}}}return context; // 返回响应内容
}
调用get接口
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.commons.lang3.StringUtils; import java.io.IOException; public static String doGetWeChat(String accessToken, String url, String tradeCode) throws IOException { // 创建一个默认的 HTTP 客户端实例 try (CloseableHttpClient client = HttpClients.createDefault()) { // 创建 HTTP GET 请求对象,并添加查询参数(如果需要的话) // 注意:这里假设url已经包含了所有必要的查询参数,或者我们将通过StringBuilder来动态构建它 // 如果需要添加查询参数,可以使用URIBuilder HttpGet method = new HttpGet(url + "?accessToken=" + accessToken + "&tradeCode=" + tradeCode); // 配置请求超时时间(可选,根据需要设置) // 如果不需要,可以省略这一步 // ...(与POST请求中相同的配置方式) // 发送请求并获取响应 try (CloseableHttpResponse response = client.execute(method)) { // 获取响应实体 String context = EntityUtils.toString(response.getEntity(), "UTF-8"); // 将响应实体转换为字符串(UTF-8 编码) // 可以在这里添加对响应状态码的检查 // 例如:if (response.getStatusLine().getStatusCode() == 200) { ... } return context; // 返回响应内容 } } catch (IOException e) { // 处理可能的异常,比如网络问题、解析问题等 throw e; // 或者根据需要处理异常,比如记录日志、返回错误信息等 }
} // 注意:
// 1. 这里使用了try-with-resources语句来自动关闭CloseableHttpClient和CloseableHttpResponse,以确保资源被正确释放。
// 2. 如果URL中包含敏感信息(如accessToken),请确保使用HTTPS来保护通信安全。
// 3. 如果URL中的查询参数较多或构建逻辑较复杂,建议使用URIBuilder来构建URL,以避免URL编码等问题。