使用HttpClient发送InputStream对象

一、使用背景

       在应用服务平台(B服务)由用户填写相关信息,应用服务根据信息调用第三方平台(A服务)获取文件,应用平台再需要将第三方平台返回的文件流发送至文件服务平台(C服务),文件服务平台保存文件后将相关保存信息返回至应用服务平台。

使用背景

二、需要导入的jar包

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.3.1</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.3.1</version>
</dependency>

三、JAVA后台代码

    3.1 从第三方服务获取文件(InputStream)

/**
  * 从第三方服务获取文件
  * paramsJSON 用户填写的相关信息
  * req Http请求
  * result 返回结果
  */
public JSONObject downloadByLicenseId(JSONObject paramsJSON, HttpServletRequest req, JSONObject result) throws Exception {
    String licenseId = paramsJSON.getString("licenseId");
    String filename = paramsJSON.getString("filename");
    filename = URLDecoder.decode(filename, "UTF-8");
    String licenseNumber = paramsJSON.getString("licenseNumber");
    InputStream inputStream = null;
    try {
        // 1.创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 2.创建post方式请求对象
        HttpPost httpPost = new HttpPost("此处填写实际访问路径");
        // 3.填写参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("licenseId", licenseId));
        // 4.将参数添加至请求消息中
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        // 5.设置消息头
        httpPost.setHeader("Accept-Charset", "utf-8");
        httpPost.setHeader("Accept-Encoding", "identity");// 在请求中明确定义不要进行压缩
        // 6.发送消息,获取响应
        CloseableHttpResponse res = httpClient.execute(httpPost);
        if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            // 7.拿到响应结果实体
            HttpEntity entity = res.getEntity();
            if(entity != null) {
                // 8.获取响应类型
                Header header = entity.getContentType();
                // 获取响应头部信息
                if(header.toString().contains("application/ofd")) {    // .1.返回的是文件流
                    inputStream = entity.getContent();
                    // save:将文件保存至文件服务器
                    JSONObject fileInfo = savaFileToFtp(inputStream, filename + ".ofd");
                    fileInfo.put("licenseId", licenseId);
                    fileInfo.put("licenseNumber", licenseNumber);
                    result.put("success", true);
                    result.put("fileInfo", fileInfo);
                } else {   // .2.返回的是错误信息 
                    String resultMsg = EntityUtils.toString(entity);
                    JSONObject resultJson = JSONObject.parseObject(resultMsg);
                    result.put("success", false);
                    result.put("msg", (resultJson.getJSONObject("head").getString("message"));
                }
            }
            // 8.释放资源
            EntityUtils.consume(entity);
        } else {
            result.put("errorCode", res.getStatusLine().getStatusCode() + "");
        }
        // 9.关闭连接
        res.close();
    } catch (Exception e) {
       result.put("errorCode", "500");
       result.put("msg", e.getMessage());
       e.printStackTrace();
    } finally {
       if (inputStream != null) {
           try {
               inputStream.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
    }
    return result;
}

    3.2 将InputStream通过HttpClient发送至文件服务器

/** 调用外部接口上传至FTP */
public JSONObject savaFileToFtp(InputStream ins, String fileName) throws ClientProtocolException, IOException {
    SONObject fileInfo = new JSONObject();
    // 1.创建httpclient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 2.创建post方式请求对象
    HttpPost httpPost = new HttpPost("http://" + ftpip + ":8083/file/zzuploads");
    // 3.创建MultipartEntityBuilder实例
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setCharset(Charset.forName("utf-8"));
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    /*
     * 第一个参数为文件服务器中接口方法的文件参数
     * 第二个参数为InputStream对象
     * 第三个参数为请求数据类型
     * 第四个参数为文件名
     */
    builder.addBinaryBody("filedata", ins, ContentType.MULTIPART_FORM_DATA, fileName);
    // 4.将文件数据添加至请求消息中
    HttpEntity entity = builder.build();
    httpPost.setEntity(entity);
    // 5.发送消息,获取响应
    CloseableHttpResponse res = httpClient.execute(httpPost);
    if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
        entity = res.getEntity();
        if(entity != null) {
            String resultMsg = EntityUtils.toString(entity);
            fileInfo = JSONObject.parseObject(resultMsg);
        }
    }
    // 6.释放资源
    EntityUtils.consume(entity);
    return fileInfo;
}
发布了47 篇原创文章 · 获赞 16 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/zorro_jin/article/details/90743467