HttpClient4.X发送带参数的Get请求
2023-03-14 10:23:50 时间
HttpClient 是apache 组织下面的一个用于处理HTTP 请求和响应的开源工具。所用jar包为httpclient-4.3.6.jar、httpcore-4.3.3.jar、httpmime-4.3.6.jar、commons-codec-1.6.jar。
发送Get请求代码如下:
package com.zkn.newlearn.httpclient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.entity.UrlEncodedFormEntity; 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.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import com.google.common.collect.Lists; public class HttpClientTest02 { public static void main(String[] args) { CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; InputStream is = null; String url = "http://localhost:8080/MyWebxTest/getCityByProvinceEname.do"; //封装请求参数 List<NameValuePair> params = Lists.newArrayList(); params.add(new BasicNameValuePair("cityEname", "henan")); String str = ""; try { //转换为键值对 str = EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8)); System.out.println(str); //创建Get请求 HttpGet httpGet = new HttpGet(url+"?"+str); //执行Get请求, response = httpClient.execute(httpGet); //得到响应体 HttpEntity entity = response.getEntity(); if(entity != null){ is = entity.getContent(); //转换为字节输入流 BufferedReader br = new BufferedReader(new InputStreamReader(is, Consts.UTF_8)); String body = null; while((body=br.readLine()) != null){ System.out.println(body); } } } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ //关闭输入流,释放资源 if(is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } //消耗实体内容 if(response != null){ try { response.close(); } catch (IOException e) { e.printStackTrace(); } } //关闭相应 丢弃http连接 if(httpClient != null){ try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
相关文章
- 在 Go 里用 CGO?这 7 个问题你要关注!
- 9款优秀的去中心化通讯软件 Matrix 的客户端
- 求职数据分析,项目经验该怎么写
- 在OKR中,我看到了数据驱动业务的未来
- 火山引擎云原生大数据在金融行业的实践
- OpenHarmony富设备移植指南(二)—从postmarketOS获取移植资源
- 《数据成熟度指数》报告:64%的企业领袖认为大多数员工“不懂数据”
- OpenHarmony 小型系统兼容性测试指南
- 肯睿中国(Cloudera):2023年企业数字战略三大趋势预测
- 适用于 Linux 的十大命令行游戏
- GNOME 截图工具的新旧截图方式
- System76 即将推出的 COSMIC 桌面正在酝酿大变化
- 2GB 内存 8GB 存储即可流畅运行,Windows 11 极致精简版系统 Tiny11 发布
- 迎接 ecode:一个即将推出的具有全新图形用户界面框架的现代、轻量级代码编辑器
- loongarch架构介绍(三)—地址翻译
- Go 语言怎么解决编译器错误“err is shadowed during return”?
- 敏捷:可能被开发人员遗忘的部分
- Denodo预测2023年数据管理和分析的未来
- 利用数据推动可持续发展
- 在 Vue3 中实现 React 原生 Hooks(useState、useEffect),深入理解 React Hooks 的