美文网首页程序员
Apache HttpClient发送POST请求

Apache HttpClient发送POST请求

作者: 子夜小事 | 来源:发表于2019-03-25 17:46 被阅读9次

    Apache的HttpClient是常用的HTTP请求工具组件,从业多年,该组件的版本已经更新多次,之前熟悉的代码已经不能使用了,一些类都还删除了。

    一般在公司使用时候都会进行封装,这次是新项目,需要调用保险公司的文件服务器上传文件,也算是从零开始再了解一次。全部代码如下:

    package com.henryge.life.pms.util;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    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.mime.MultipartEntityBuilder;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.input.SAXBuilder;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.util.HashMap;
    import java.util.Map;
    
    public class InsuranceFileUtil {
    
        private final static Logger LOGGER = LoggerFactory.getLogger(InsuranceFileUtil.class);
    
        public static Map<String, Object> uppload(String url, MultipartFile file) throws Exception {
            CloseableHttpClient client = HttpClients.createDefault();
            Map<String, Object> resultMap = new HashMap<>();
    
            String fileName = file.getOriginalFilename();
            HttpPost httpPost = new HttpPost(url + "upload.do");
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody(fileName, file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
            builder.addTextBody("systemName", "test");
            builder.addTextBody("userName", "test");
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
    
            HttpResponse response = client.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
    
            SAXBuilder sb = new SAXBuilder();
            Document doc = sb.build(responseEntity.getContent());
            Element root = doc.getRootElement();
    
            resultMap.put("fileId", root.getChild("attachment").getChildText("fileid"));
            resultMap.put("downloadUrl", url + "download.do?fileid=" + resultMap.get("fileId").toString());
            return resultMap;
        }
    
        public static Object[] download(String url) throws Exception {
            CloseableHttpResponse response = null;
            CloseableHttpClient client = null;
            try {
                client = HttpClients.createDefault();
                HttpGet httpGet = new HttpGet(url);
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                if (entity == null) {
                    return new Object[]{};
                } else {
                    LOGGER.info("StatusCode is " + response.getStatusLine().getStatusCode());
                    if (response.getStatusLine().getStatusCode() == 200) {
                        return new Object[]{entity.getContent()};
                    } else {
                        return new Object[]{};
                    }
                }
            } finally {
    
                if (response != null) {
                    try {
                        response.close();
                    } catch (Exception var28) {
                    }
                }
    
                if (client != null) {
                    try {
                        client.close();
                    } catch (Exception var27) {
                    }
                }
    
            }
        }
    
    }
    

    HttpClients.createDefault();初始化一个CloseableHttpClient,调用的是HttpClientBuilder.build()方法。使用MultipartEntityBuilder来组装请求参数,addBinaryBodyaddTextBody均是填充请求参数,底层都是调用方法:
    public MultipartEntityBuilder addPart(final FormBodyPart bodyPart) { if (bodyPart == null) { return this; } if (this.bodyParts == null) { this.bodyParts = new ArrayList<FormBodyPart>(); } this.bodyParts.add(bodyPart); return this; }

    相关文章

      网友评论

        本文标题:Apache HttpClient发送POST请求

        本文链接:https://www.haomeiwen.com/subject/ayebvqtx.html