httpclient3发送文件流

情境:web端上传文件到本地,本地使用httpclient转发到接口服务器存储。

 1 //前期经过处理,其中list中为表单数据,ins中为文件流
 2 PostMethod post = new PostMethod(url);
 3 post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
 4 
 5 List<Part> parts = new ArrayList<Part>();
 6 
 7 if (list != null) {
 8     int len = list.size();
 9     for (int i = 0; i < len; i++) {
10         parts.add(new StringPart(list.get(i).getName(),list.get(i).getValue()));
11     }
12 }
13 if(ins!=null && ins.size()>0){
14     for (Map.Entry<String, InputStream> entry : ins.entrySet()) {
15         //entry.getKey();文件名 entry.getValue();文件流
16         //将InputStream转到FilePart格式
17         parts.add(new FilePart(entry.getKey(), new ByteArrayPartSource(entry.getKey(), getByte(entry.getValue()))));
18     }
19 }
20 HttpMethodParams params = post.getParams();
21 Part[] partArray = new Part[parts.size()];
22 MultipartRequestEntity mlEntity = new MultipartRequestEntity(parts.toArray(partArray),params);
23 post.setRequestEntity(mlEntity);

 

转载于:https://www.cnblogs.com/chiying/p/5485964.html

您可以使用 Java 的 HttpClient 库来获取文件流。以下是一个简单的示例代码: ```java 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.util.EntityUtils; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Main { public static void main(String[] args) { String fileUrl = "http://example.com/file.txt"; String savePath = "path/to/save/file.txt"; try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpGet httpGet = new HttpGet(fileUrl); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { InputStream inputStream = response.getEntity().getContent(); OutputStream outputStream = new FileOutputStream(savePath); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } ``` 上述代码使用 HttpClient 发送 GET 请求获取文件流,并将其保存到本地文件中。您需要将 `fileUrl` 替换为要下载的文件的 URL,将 `savePath` 替换为文件保存的路径和文件名。请确保添加 HttpClient 库的依赖到您的项目中。 这样,您就可以通过 HttpClient 获取文件流并保存到本地文件中了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值