Java使用HttpClient发送post请求

package com.firefly.performance.core.utils;

import com.firefly.performance.api.enums.performance.ExportFineReportEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author zhangping
 */
@Slf4j
@Component
public class FineReportUtils {

    @Value("${fineReportUrl}")
    private String fineReportUrl;

    @Value("${fineReportPath}")
    private String fineReportPath;

    /**
     * 帆软导出pdf
     * @param exportFineReportEnum
     * @param requestParams
     * @param response
     */
    public void exportFineReportPdf(ExportFineReportEnum exportFineReportEnum, Object requestParams, HttpServletResponse response) {
        String uri = String.format("%s?viewlet=%s%s&format=pdf", fineReportUrl, fineReportPath, exportFineReportEnum.getCptFile());
        String attachmentName = exportFineReportEnum.getExportName();
        exportPdf(requestParams, response, uri, attachmentName);
    }

    /**
     * 发送post请求至帆软
     * @param requestParams
     * @param response
     * @param uri
     * @param attachmentName
     */
    private void exportPdf(Object requestParams, HttpServletResponse response, String uri, String attachmentName) {
        HttpPost post = new HttpPost(uri);
        HttpEntity entity = new UrlEncodedFormEntity(ofList(requestParams), StandardCharsets.UTF_8);
        post.setEntity(entity);
        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             ServletOutputStream outputStream = response.getOutputStream();
             CloseableHttpResponse fileResponse = httpClient.execute(post)){
            Assert.fail(HttpStatus.OK.value() != fileResponse.getStatusLine().getStatusCode(),"绩效请求帆软服务器返回异常!");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(attachmentName, "UTF-8"));
            response.setHeader("Content-type", "application/pdf");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            fileResponse.getEntity().writeTo(outputStream);
        } catch (Exception e) {
            log.error("帆软导出失败:{}", e);
            Assert.fail(Boolean.TRUE,"帆软导出失败!");
        }
    }

    public List ofList(Object requestParams) {
        if (requestParams == null) {
            return new ArrayList<>();
        }
        ArrayList list = new ArrayList<>();
        Field[] declaredFields = requestParams.getClass().getDeclaredFields();
        Arrays.stream(declaredFields).forEach(field -> {
            field.setAccessible(true);
            try {
                String name = field.getName();
                Object fieldValue = field.get(requestParams);
                if (fieldValue != null) {
                    if (fieldValue instanceof Date) {
                        fieldValue = DateUtil.format((Date) fieldValue, "YYYY-MM-dd");
                    }
                    if (fieldValue instanceof Collection) {
                        //noinspection rawtypes
                        fieldValue = join((Collection) fieldValue);
                    }
                    list.add(new BasicNameValuePair(name, fieldValue.toString()));
                }
            } catch (IllegalAccessException e) {
                log.error("", e);
            }
            field.setAccessible(false);
        });
        return list;
    }

    private String join(@SuppressWarnings("rawtypes") Collection fieldValue) {
        if (fieldValue == null || fieldValue.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (Object item : fieldValue) {
            if (item instanceof Number) {
                if (sb.length() > 0) {
                    sb.append(",");
                }
                sb.append(item);
            }
            if (item instanceof String) {
                if (sb.length() > 0) {
                    sb.append(",");
                }
                sb.append("'").append(item).append("'");
            }
        }
        return sb.toString();
    }
}

你可能感兴趣的:(java)