HttpClient——概述(一)

简介: httpClient使用简介,以及常用的方法,

一、HttpClient scope

1.Client-side HTTP transport library based on HttpCore
2.Based on classic (blocking) I/O
3.Content agnostic

二、HttpClient能做什么?

1.HttpClient不是浏览器
2.HttpClient只能发送、接收请求,传输数据
3.HttpClient不解析返回数据


支持的请求类型
GET, HEAD, POST, PUT, DELETE, TRACE and OPTIONS.
对应的方法类型
HttpGet,HttpHead, HttpPost, HttpPut, HttpDelete, HttpTrace, HttpOptions.

三、执行请求的基本代码块


CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
    <...>
} finally {
    response.close();
}



HttpRequestType

四、Http Request URI的组成与HTTP请求

HTTP request URIs consist of a protocol scheme, host name, optional port, resource path, optional query, and optional fragment.

URI uri = new URIBuilder()
        .setScheme("http")
        .setHost("www.google.com")
        .setPath("/search")
        .setParameter("q", "httpclient")
        .setParameter("btnG", "Google Search")
        .setParameter("aq", "f")
        .setParameter("oq", "")
        .build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());

stdout

http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq=


五、HTTP Response(这个是指我们调用接口后需要返回消息体给对方)


HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 
HttpStatus.SC_OK, "OK");

System.out.println(response.getProtocolVersion());
System.out.println(response.getStatusLine().getStatusCode());
System.out.println(response.getStatusLine().getReasonPhrase());
System.out.println(response.getStatusLine().toString());



stdout

HTTP/1.1
200
OK
HTTP/1.1 200 OK


六、设置响应头

读取head的时候有两种方式:
方式一:

HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 
    HttpStatus.SC_OK, "OK");
response.addHeader("Set-Cookie", 
    "c1=a; path=/; domain=localhost");
response.addHeader("Set-Cookie", 
    "c2=b; path=\"/\", c3=c; domain=\"localhost\"");
Header h1 = response.getFirstHeader("Set-Cookie");
System.out.println(h1);
Header h2 = response.getLastHeader("Set-Cookie");
System.out.println(h2);
Header[] hs = response.getHeaders("Set-Cookie");
System.out.println(hs.length);

方式二: 使用HeaderIterator

HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 
    HttpStatus.SC_OK, "OK");
response.addHeader("Set-Cookie", 
    "c1=a; path=/; domain=localhost");
response.addHeader("Set-Cookie", 
    "c2=b; path=\"/\", c3=c; domain=\"localhost\"");

HeaderIterator it = response.headerIterator("Set-Cookie");

while (it.hasNext()) {
    System.out.println(it.next());
}


七、HTTP Entity (HTTP消息实体)

消息体存在于请求体或者响应体中,HttpClient通过内容的源来区分三种消息体:
streamed:
The content is received from a stream, or generated on the fly. Streamed entities are generally not repeatable.
self-contained:
Self-contained entities are generally repeatable, will be mostly used for entity enclosing HTTP requests
wrapping:
The content is obtained from another entity.
补充:The HTTP specification defines two entity enclosing request methods: POST and PUT.


处理流类型消息体时,注意释放资源

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        try {
            // do something useful
        } finally {
            instream.close();
        }
    }
} finally {
    response.close();
}



The difference between closing the content stream and closing the response is that the former will attempt to keep the underlying connection alive by consuming the entity content while the latter immediately shuts down and discards the connection.
译:关闭流消息体和关闭响应的区别是前者通过消费(读取)消息体的内容的方式尝试保持连接的存活,而后者则是立即断开连接。—— (有待于纠正)

在我们使用streaming entities时,我们也可以使用EntityUtils.consume(HttpEntity) 方法来确保消息体的内容全部被读完(or has been fully consumed),并且Stream连接已经关闭。


处理包装类型的资源:(使用背景:在我们想多次使用content的时候我们需要缓存资源)

CloseableHttpResponse response = <...>
HttpEntity entity = response.getEntity();
if (entity != null) {
    entity = new BufferedHttpEntity(entity);
}


未完待续....

目录
相关文章
|
3月前
|
人工智能 自然语言处理 监控
适合电商的智能客服产品推荐:从功能匹配到价格对比全解析
本文深度解析阿里云瓴羊Quick Service如何赋能电商客服升级:依托AI Agent实现退换货等闭环办事,全渠道协同统一工作台,多源知识库自动更新,并提供模块化定价。适配大促高并发,助力企业从“问答”迈向“办事”新阶段。
|
JavaScript 前端开发 关系型数据库
GIS开发:GeoJSON坐标和WKT的转换
GIS开发:GeoJSON坐标和WKT的转换
1407 0
|
5月前
|
数据采集 人工智能 自然语言处理
GEO优化怎么自己做?原理确实简单!
GEO优化是面向生成式AI搜索的新型内容策略,核心在于提升品牌在ChatGPT、Perplexity等引擎中的引用率。其难点不在原理,而在规模化落地:人工操作效率低、效果难归因、缺乏闭环数据追踪。自建系统需覆盖结构化内容生成、多平台智能分发与引用效果追踪三层架构,实现从“黑盒运营”到“数据驱动”的质变。(239字)
|
5月前
|
人工智能 并行计算 iOS开发
openclaw一键部署脚本更新,TopClaw支持最新模型及多平台适配
TopClaw是国产优化版OpenClaw,支持一键部署、自动适配Windows/macOS(含Apple Silicon)、免配置运行。内置Qwen2.5、DeepSeek等最新模型,性能提升30%-50%,全程离线、隐私安全,小白3分钟即可上手。
477 0
|
7月前
|
SQL 域名解析 运维
线上服务变慢,到底慢在哪?一份给后端和运维的网络分层排障手册
凌晨 2 点告警炸了:服务 P99 从 200ms 飙到 8s,但 CPU、内存、慢 SQL 全部正常——问题往往藏在你看不到的网络链路里。本文沉淀一套从 DNS、链路、TCP/TLS、HTTP 到 IP 信誉的「五层分层排障方法论」,配合命令行实操和真实案例,给后端、运维、SRE 同学一份可以直接抄进 Runbook 的网络排障手册。
887 3
|
人工智能 自然语言处理 搜索推荐
2025年11月,中国数字人平台介绍及应用场景全解析
2025年,数字人技术加速落地,凭借AI、图形学与多模态交互融合,广泛应用于金融、教育、政务等领域。
|
5月前
|
人工智能 监控 安全
Claude 插件市场突然起飞:我按开发者视角拆了一遍,发现它不只是“插件合集”
Anthropic 官方 Claude 插件市场(31k+ Star),标志着 AI 编程工具从“提示词调教”迈向标准化插件生态。支持 LSP、MCP、子智能体等能力打包分发,实现可安装、可治理的 Agent 能力模块化,是 Claude Code 迈向平台化的重要里程碑。(239字)
549 1
|
6月前
|
人工智能 自然语言处理 API
阿里云计算巢一键部署DeepSeek-TUI: DeepSeek 版的 Claude Code 终端AI编程实操教程
在AI编程工具飞速迭代的当下,终端类智能编码助手凭借轻量化、无依赖、高效流畅的特性,深受开发者青睐。DeepSeek-TUI作为对标Claude Code的终端原生编程智能体,基于DeepSeek V4系列模型深度打造,能够直接在命令行中完成代码生成、项目搭建、脚本编写、漏洞排查、网页检索、Git管理等全流程开发工作,凭借强大的上下文能力与完备工具链,迅速在开发者社区走红。
552 2
|
移动开发 前端开发 JavaScript
Canvas 绘图基础
Canvas是HTML5的绘图API,通过JavaScript实现像素级图形、动画和游戏开发。支持矩形、路径、圆形、文本、图像及渐变绘制,结合requestAnimationFrame可制作高性能动画,广泛应用于数据可视化、游戏与交互设计。
1357 11
|
11月前
|
运维 监控 安全
IT运维事故复盘工具指南:从应急响应到体系化改进的全流程解析
在数字化时代,IT运维事故频发,复盘不应追责,而应推动系统性改进。通过结构化复盘,还原时间线、量化影响、深挖根因、落实可追踪的优化措施,将事故转化为能力沉淀。借助专业工具与科学方法,构建“记录-分析-改进-验证”闭环,提升组织韧性与抗风险能力,实现从被动“救火”到主动“防火”的跨越。