HttpClient传输文件遇到的Bug

HttpClient传输遇到的Bug

请先熟悉Postman软件

(这是windows 64位的)
下载地址:https://www.getpostman.com/download?platform=win64

测试软件软件:Postman
请求类型:post

代码:

import org.apache.http.HttpEntity;
import org.apache.http.ProtocolVersion;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
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.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class HttpHttpPostDemo {
    private static final String AUTH_VALUE = "密钥";
    //(这里的密钥是从Postman软件里的Header中的Authorization的value获取的)
    //访问HTTP协议及版本
    private static final ProtocolVersion HTTP_1_0 = new ProtocolVersion("HTTP", 1, 0);
    public static void runGETExample(String getAddress,String docfileid) throws Exception {
        if(getAddress==null||getAddress.length()==0)
            throw new IllegalArgumentException("getAddress can not be null");
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(getAddress+"/"+docfileid);
            httpGet.setProtocolVersion(HTTP_1_0);
            // 必须增加的request头部信息
            httpGet.addHeader("authorization", "Basic "+AUTH_VALUE);
            httpGet.addHeader("cache-control", "no-cache");
            httpGet.addHeader("accept", ContentType.APPLICATION_XML.getMimeType());
            httpGet.addHeader("accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
            System.out.println( httpGet.getRequestLine());
            System.out.println(Arrays.toString(httpGet.getAllHeaders()));
            System.out.println("↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓");
            CloseableHttpResponse response = httpclient.execute(httpGet);
            try {
                //获得响应报文的状态值。
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("Response status code: "+ statusCode);

                //读取响应报文的内容
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content text: "+ EntityUtils.toString(resEntity,"UTF-8"));
                }
                //如果读取内容一定要记得释放响应报文。该函数就是关闭resEntity.getContent()这个InputStream用的。
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        }finally{
            httpclient.close();
        }
    }

    public static void runPOSTExample(String postAddress,String docxmlfile,String docfile) throws Exception {
        if(postAddress==null||postAddress.length()==0)
            throw new IllegalArgumentException("postAddress can not be null");
        //新建HTTPClient对象。这个对象要在finally里面关闭。
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // POST请求的地址
            HttpPost httppost = new HttpPost(postAddress);
            httppost.setProtocolVersion(HTTP_1_0);
            // 必须增加的request头部信息
            httppost.addHeader("authorization", "Basic "+AUTH_VALUE);
            httppost.addHeader("cache-control", "no-cache");
            httppost.addHeader("accept", ContentType.APPLICATION_XML.getMimeType());
            httppost.addHeader("accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");

            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .addPart("medicaldocxml", new FileBody(new File(docxmlfile)))
                    .addPart("medicaldocfile", new FileBody(new File(docfile)))
                    .build();//组装归档文件描述XML文件和归档文件做为请求的内容
            // 组装POST请求
            httppost.setEntity(reqEntity);
            System.out.println( httppost.getRequestLine());
            System.out.println(Arrays.toString(httppost.getAllHeaders()));
            System.out.println(httppost.getEntity().getContentType());
            System.out.println(EntityUtils.toString(httppost.getEntity()));
            System.out.println("↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓");
            // 发送POST请求。并获得响应报文
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println(Arrays.toString(response.getAllHeaders()));
                System.out.println(response.getStatusLine());
                //获得响应报文的状态值。
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("Response status code: "+ statusCode);
                //读取响应报文的内容
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content text: "+ EntityUtils.toString(resEntity,"UTF-8"));
                }
                //如果读取内容一定要记得释放响应报文。该函数就是关闭resEntity.getContent()这个InputStream用的。
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

    public static void main(String[] args) throws Exception {
        System.out.println("---------------HTTP POST-------------");
        HttpHttpPostDemo.runPOSTExample(
                "请求的ip地址",
                "归档文件描述XML",
                "归档文件路径"
        );
        //System.out.println("---------------HTTP GET--------------");
        HttpHttpPostDemo.runGETExample("请求的地址","文件唯一标识");
    }
}

post方法是用来上传文件的
get方法是用来获取传输的状态值的

Bug: Cause by: 2 字节的 UTF-8 序列的字节 2 无效
解决方案:xml记事本打开->另存为->下边勾选utf-8编码格式(仅此而已)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Apache HttpClient是一个流行的Java库,用于处理HTTP请求。如果你想使用HttpClient从网络下载文件,你可以按照以下步骤操作: 1. **添加依赖**: 首先,你需要将HttpClient依赖加入到你的项目中。如果你使用Maven,可以在pom.xml中添加以下依赖: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.x.y</version> <!-- 更新到最新稳定版本 --> </dependency> ``` 其他构建工具如Gradle也类似,引入对应的HttpComponents库。 2. **创建连接**: 创建一个`CloseableHttpResponse`实例来代表HTTP响应,然后获取输入流(InputStream): ```java HttpClient httpClient = HttpClients.createDefault(); HttpGet request = new HttpGet("http://example.com/file.zip"); CloseableHttpResponse response = httpClient.execute(request); try (InputStream is = response.getEntity().getContent()) { //... } ``` 3. **下载文件**: 使用`FileOutputStream`写入输入流到本地文件: ```java File outputFile = new File("path/to/download/file.zip"); FileOutputStream fos = new FileOutputStream(outputFile); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { fos.write(buffer, 0, bytesRead); } fos.close(); is.close(); ``` 4. **关闭资源**: 别忘了在完成文件写入后关闭所有打开的连接和流,释放系统资源: ```java response.close(); httpClient.getConnectionManager().shutdown(); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值