Jenkins流水线调用外部API下载.xls文件出现损坏问题求解
Jenkins流水线httpRequest下载Excel文件损坏问题解决方案
问题原因
Jenkins HTTP Request插件默认会将所有响应内容按文本格式做编码转换,Excel属于二进制文件,转换过程中会篡改原始字节数据,导致文件损坏。Postman对二进制响应不会做额外编码转换,因此可以正常下载文件。
解决方案
- 方案1:添加
acceptType参数明确指定接收二进制流,禁用插件的文本编码转换逻辑,修改后的调用代码如下:
def response = httpRequest( customHeaders: [[maskValue: false, name: 'Accept', value: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']], acceptType: 'APPLICATION_OCTET_STREAM', outputFile: './abc.xls', url: 'http://xyz/', wrapAsMultipart: false, consoleLogResponseBody: false )
consoleLogResponseBody: false为可选参数,作用是避免二进制内容输出到控制台导致日志混乱。
- 方案2:如果方案1无效,大概率是服务端返回了gzip等压缩格式的响应,插件自动解压时出错,可以添加
Accept-Encoding请求头强制服务端返回未压缩的内容:
def response = httpRequest( customHeaders: [ [maskValue: false, name: 'Accept', value: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'], [maskValue: false, name: 'Accept-Encoding', value: 'identity'] ], acceptType: 'APPLICATION_OCTET_STREAM', outputFile: './abc.xls', url: 'http://xyz/', wrapAsMultipart: false, consoleLogResponseBody: false )
- 方案3:如果使用的HTTP Request插件版本过旧不支持上述参数,可以直接使用Groovy原生HTTP客户端下载文件,绕过插件的处理逻辑:
// 需提前确认Jenkins脚本安全配置允许调用对应方法 def outputPath = new File("${WORKSPACE}/abc.xls") def apiUrl = new URL("http://xyz/") def conn = apiUrl.openConnection() conn.setRequestMethod("GET") conn.setRequestProperty("Accept", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") conn.getInputStream().withStream { inputStream -> outputPath.newOutputStream().withStream { outputStream -> outputStream << inputStream } }
内容的提问来源于stack exchange,提问作者Sachin Jagtap
相关产品推荐
相关产品推荐

