Send InputStream object using HttpClient

First, use the background

       In the Application Service Platform (B Services) filled out by the user information, application services based on the information acquired file to call third-party platforms (A service), application platform and then you need to file a third-party platform of the stream is sent to the file server platform (C service) , file services platform will save the file to save the relevant information back to the application service platform.

Use Background

Second, the need to import jar package

<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>

Three, JAVA code-behind

    3.1 get the file from a third-party service (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 will be sent to a file server by 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;
}

 

Published 47 original articles · won praise 16 · views 70000 +

Guess you like

Origin blog.csdn.net/zorro_jin/article/details/90743467