httpclient 基础教程
- httpclient依懒包官网下载及httpclient maven依懒包获取
- httpClient快速入门
- httpclient get请求
- httpclient 带参数 get 请求
- httpclient post 请求
- httpclient 模拟浏览器请求
- httpclient post 表单参数请求
- HttpClient PUT请求示例
- HttpClient DELETE请求示例
httpclient 进阶教程
知识点
相关文章
更多最近更新
更多HttpClient 上传文件
2019-04-09 23:05|来源: 网路
在本教程中,我们将演示如何使用Apache HttpClient 4.5进行分段上传http请求。
Maven依赖关系
我们使用maven来管理依赖关系,并使用Apache HttpClient 4.5版本。 将以下依赖项添加到您的项目中。
pom.xml 文件的内容如下 -
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.yiibai.httpclient.httmethods</groupId> <artifactId>http-get</artifactId> <version>1.0.0-SNAPSHOT</version> <url>https://memorynotfound.com</url> <name>httpclient - ${project.artifactId}</name> <dependencies> <!-- Apache Commons IO --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
HttpClient分段上传请求示例
在这个例子中,我们将演示如何使用HttpClient 4.5来分段上传文件。 我们使用MultipartEntityBuilder
创建一个HttpEntity。 当创建构建器时,添加一个二进制体 - 包含将要上传的文件以及一个文本正文。 接下来,使用RequestBuilder
创建一个HTTP请求,并分配先前创建的HttpEntity
。
文件:HttpClientMultipartUploadExample.java -
import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.File; import java.io.IOException; /** * This example demonstrates the use of {@link HttpPost} request method. * And sending Multipart Form requests */ public class HttpClientMultipartUploadExample { public static void main(String... args) throws IOException { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { File file = new File(HttpClientMultipartUploadExample.class.getResource("/java-duke.png").getFile()); String message = "This is a multipart post"; // build multipart upload request HttpEntity data = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, file.getName()) .addTextBody("text", message, ContentType.DEFAULT_BINARY) .build(); // build http request and assign multipart upload data HttpUriRequest request = RequestBuilder .post("http://httpbin.org/post") .setEntity(data) .build(); System.out.println("Executing request " + request.getRequestLine()); // Create a custom response handler ResponseHandler<String> responseHandler = response -> { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } }; String responseBody = httpclient.execute(request, responseHandler); System.out.println("----------------------------------------"); System.out.println(responseBody); } } }
所有先前的分段文件上传都包含在带有相应标头消息中。执行上面示例代码,得到以下结果 -
Executing request POST http://httpbin.org/post HTTP/1.1 ---------------------------------------- { "args": {}, "data": "", "files": { "upfile": "data:application/octet-stream;base64,iVBORw0KGgoAAAANSUhEUgAAAj....." }, "form": { "text": "This is a multipart post" }, "headers": { "Accept-Encoding": "gzip,deflate", "Connection": "close", "Content-Length": "53697", "Content-Type": "multipart/form-data; boundary=SqncIg58wNoviG6dWynFmxPJnvICdQg", "Host": "httpbin.org", "User-Agent": "Apache-HttpClient/4.5.5 (Java/1.8.0_65)" }, "json": null, "origin": "112.67.166.104", "url": "http://httpbin.org/post" }
相关问答
更多-
httpclient如何一起上传内容和图片[2022-03-09]
以文件的形式传参 /** * 通过拼接的方式构造请求内容,实现参数传输以及文件传输 * * @param actionUrl 访问的服务器URL * @param params 普通参数 * @param files 文件参数 * @return * @throws IOException */ public static void post(String actionUrl, Mapparams, Map files) throws IOExc ... -
如何执行使用webapi HttpClient文件上传多后[2022-03-29]
HttpClient c = new HttpClient(); var fileContent = new ByteArrayContent(new byte[100]); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "myFilename.txt" }; var formData = new FormUrlEncodedContent(new[] ... -
这就是答案:我可以将带有多部分附件的文件从c#client发送到Java JAX Rest Webservice。 try { using ( var client = new HttpClient()) using (var form = new MultipartFormDataContent()) { using (var stream = new File ...
-
如何使用Java HttpClient库使用PHP上传文件(How to upload a file using Java HttpClient library working with PHP)[2023-09-11]
好的,我使用的Java代码是错误的,这里有正确的Java类: import java.io.File; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import ... -
这一切都非常简单。 在前一种情况下,可以在已知其所有部分的长度的情况下计算多部分实体内容的总长度。 此类实体可以包含在由Content-Length标头分隔的请求中。 在后一种情况下,不能确定总实体长度,并且利用块编码来发送请求。 显然,一些具有有限协议合规性的服务器端脚本无法处理没有Content-Length标头的请求。 That is all very simple. In the former case the total length of the multipart entity content ...
-
Java OutputStream文件使用httpclient上传性能(Java OutputStream file upload performances using httpclient)[2022-04-26]
你应该试试https://hc.apache.org/ 您可以将httpclient库更改为基于java.nio的库: https : //docs.oracle.com/javase/7/docs/api/java/nio/package-summary.html HttpCore是一组低级HTTP传输组件,可用于以最小的占用空间构建自定义客户端和服务器端HTTP服务。 HttpCore支持两种I / O模型:基于经典Java I / O的阻塞I / O模型和基于Java NIO的非阻塞,事件驱动的I / ... -
在我的一个项目中,我使用了这样的东西。 希望能帮助到你。 [[[RKObjectManager sharedManager] HTTPClient] multipartFormRequestWithMethod:RKRequestMethodPOST path:@"somePath" parameters:nil constructingBodyWithBlock:^(id
formData) { NSString *fileName = @""; ... -
为了简化您的故障排除并了解发生的情况: 打开HttpClient线路级日志记录 使用LiveHttpHeaders或类似的插件来了解浏览器如何处理这个问题 使用WireShark或类似工具检查网络级流量 然后, 比较浏览器和HttpClient之间的差异 。 我注意到的一件事是:在您的代码中,您将视频发布为“userfile”参数,但PandaStream API文档说您应该使用“file”参数。 但不确定它是否有所作为。 即使参数名称错误,PandaStream仍应返回正确的响应,而不仅仅是在出错时关闭连 ...
-
HttpClient通过PostAsync上传文件的奇怪行为(Weird behavior of HttpClient uploading file via PostAsync)[2024-02-28]
在您的代码中, client.PostAsync立即返回(当操作在后台继续)。 这将展开两个using语句,因此在上载完成之前 HttpClient对象将被处理掉。 如果你想在这里using ,你需要使用await而不是ContinueWith : var result = await client.PostAsync(...); if (result.IsSuccessStatusCode) { // ... } 如果您需要以.NET 4.0为目标但使用VS2012 +进行开发,您仍然可以使用a ... -
覆盖FileBody.writeTo(OutputStream)以在写入时计算字节数。 这允许在上载期间和完成之后发送的字节数(即使被中断)。 public class FileBodyCounter extends FileBody { private volatile long byteCount; public long getBytesWritten() { return byteCount; } public void writeTo(Outpu ...