从socket开始实现服务器及Http请求类 [2],Chunked分块传输支持,与其它几个rest速度对比

本文介绍了如何从socket开始实现服务器,并详细讲解了Chunked分块传输的识别、接收和响应体处理。通过速度对比,发现Spring restTemplate在性能上不占优势,而.Net Core HttpClient因其异步特性表现出色。尽管C++实现较慢,但作者对其潜力保持乐观,计划进一步优化。
摘要由CSDN通过智能技术生成

项目源代码仓库 GitHub

Chunked识别
			MyString contentLen = Header["Content-Length"];
			ContentLength = contentLen != "" ? stoi(contentLen) : ContentLength;
			Cookie = Header["Cookie"];
			Server = Header["Server"];
			TransferEncoding = Header["Transfer-Encoding"];
			IsChunked = ContentLength==0;

就是这么简单粗暴,正文文本长度为0那就是Chunked

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个使用HttpPost进行chunked分块传输的示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; public class ChunkedHttpPostDemo { public static void main(String[] args) { try { // 创建HttpClient对象 HttpClient httpClient = HttpClientBuilder.create().build(); // 创建HttpPost对象,并设置URL HttpPost httpPost = new HttpPost("http://example.com/api"); // 设置请求体为chunked分块传输 StringEntity entity = new StringEntity("This is a chunked request body"); entity.setChunked(true); httpPost.setEntity(entity); // 执行请求并获取响应 HttpResponse response = httpClient.execute(httpPost); // 获取响应实体 HttpEntity responseEntity = response.getEntity(); // 解析响应内容 String responseBody = EntityUtils.toString(responseEntity); // 输出响应内容 System.out.println("Response: " + responseBody); // 关闭连接 httpClient.getConnectionManager().shutdown(); } catch (Exception e) { e.printStackTrace(); } } } ``` 这个示例代码使用Apache HttpComponents库来发送HttpPost请求。通过设置`StringEntity`的`setChunked(true)`方法,可以将请求体进行chunked分块传输。然后,将`StringEntity`对象设置到`HttpPost`对象中的`setEntity`方法中。最后,执行请求并获取响应,解析响应内容并输出。 请注意,需要添加Apache HttpComponents库的依赖,例如在Maven项目中,可以在pom.xml文件中添加以下依赖: ```xml <dependencies> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> </dependencies> ``` 希望这可以帮助到你!如果你还有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值