必须引入httpclient依赖并正确构造请求对象,否则会抛出classnotfoundexception或nullpointerexception;添加maven坐标后,get请求需创建客户端、构建请求、执行并关闭资源;post请求支持json或表单数据;超时配置需合理避免失败或阻塞。

要在Java项目中通过HttpClient发送GET或POST请求获取远程API数据,必须先引入对应依赖并正确构造请求对象,否则会抛出ClassNotFoundException或NullPointerException。
添加HttpClient依赖
打开项目的pom.xml文件,在<dependencies></dependencies>标签内插入以下Maven坐标:
这一步不能跳过——没有该依赖,编译时就会报错,连HttpClient类都找不到。
发送简单GET请求
第一步:创建CloseableHttpClient实例,推荐使用HttpClients.createDefault();
第二步:用HttpUriRequestBuilder.createGet().setUri("https://api.example.com/data").build()构造GET请求;
第三步:调用client.execute(request)获取CloseableHttpResponse响应;
第四步:用EntityUtils.toString(response.getEntity(), "UTF-8")读取响应体字符串;
第五步:务必按顺序关闭response和client,否则连接不会释放,多次调用后会触发ConnectionPoolTimeoutException。
【必须在finally块或try-with-resources中关闭response和client】
发送带JSON参数的POST请求
方法一:使用StringEntity封装JSON字符串
先用JSONObject或Jackson序列化对象为字符串→new StringEntity(jsonStr, ContentType.APPLICATION_JSON)→setEntity()到HttpPost对象→执行execute()
方法二:用UrlEncodedFormEntity提交表单数据
准备List
注意:如果服务端要求Content-Type为application/json但你传了x-www-form-urlencoded,服务器大概率返回415 Unsupported Media Type。
配置超时与重试
创建HttpClient时不要直接用createDefault(),改用自定义ConfigBuilder:
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(3000)
.setSocketTimeout(5000)
.setConnectionRequestTimeout(1000)
.build();
CloseableHttpClient client = HttpClients.custom()
.setDefaultRequestConfig(config)
.build();
超时值设得太小(如300ms)会导致弱网环境下大量请求失败;设得太大(如60秒)会让线程长时间阻塞,拖慢整个服务响应。











