Apache httpclient 获取url上的数据并向url发送参数

本文详细介绍如何使用Java通过HTTP客户端库获取URL数据,包括GET和POST请求的实现方式,并解析响应内容为JSON数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

获取url上的数据

一、添加Maven依赖

1、http依赖

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5</version>
</dependency>
2、commons依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.3.2</version>
</dependency>
3、json依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.29</version>
</dependency>

二、创建httpclient对象

CloseableHttpClient httpclient = HttpClients.createDefault();

三、HttpGet方法打开url,设置请求配置,并执行Get方法

HttpGet httpGet = new HttpGet(url);//url请求路径
RequestConfig config = RequestConfig.custom().setConnectTimeout(30000)
    .setConnectionRequestTimeout(30000).build();
httpGet.setConfig(config);
CloseableHttpResponse response = httpclient.execute(httpGet);//获取响应对象

四、判断响应内容,并进行数据处理

1、判断响应

if (null == response || null == response.getStatusLine() || null == response.getEntity()) {
    logger.error("get response error, and get response null {}", JSON.toJSONString(response));
    return null;
}
HttpEntity entry = response.getEntity();//获取响应内容
if (null == entry || !entry.isStreaming()) {
    logger.error("get data error, the return entry is null {} / or / entry is not streaming {}",
        JSON.toJSONString(response), entry.isStreaming());
}
2、读取响应内容

StringWriter writer = new StringWriter();
IOUtils.copy(entry.getContent(), writer, "UTF-8");
JSON.parseObject(writer.toString());//获取json数据

向url发送参数

一、二同上

三、HttpPost方法打开url,设置请求配置,并执行Post方法

HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body.toJSONString());
request.setEntity(params);
request.setHeader("Content-type", "application/json;charset=UTF-8");
HttpResponse response = httpClient.execute(request);
JSONObject result = JSON.parseObject(JSON.toJSONString(response.getStatusLine()));

四、判断响应内容,并进行数据处理

if(!result.containsKey("reasonPhrase") || !result.containsKey("statusCode")
     || 0!="OK".compareTo(result.getString("reasonPhrase")) || 200!=result.getInteger("statusCode") ){

//请求失败

}























评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值