Java傳送Post請求

byds520發表於2020-11-26

 1,傳送正常post請求

    public String executePost(String url, Map<String, String> params, Map<String, String> headers,
            String charSet) {
        CloseableHttpClient httpclient = getHttpClient();
        CloseableHttpResponse response = null;

        try {
            HttpPost post = new HttpPost(new URIBuilder(url).build());
            if (headers != null) {
                post.setHeaders(assemblyHeader(headers));
            }

            //  設定HTTP POST請求引數必須用NameValuePair物件
            List<NameValuePair> lst = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                lst.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            //  設定HTTP POST請求引數
            UrlEncodedFormEntity posEntity = new UrlEncodedFormEntity(lst, charSet);
            if (logger.isDebugEnabled()) {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                posEntity.writeTo(os);
                logger.debug("url:{},content:{}", url, os.toString());
            }
            post.setEntity(posEntity);
            post.setConfig(requestConfig);

            response = httpclient.execute(post);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, charSet);
        } catch (Exception e) {
            logger.error(e.getMessage() + " when url is:" + url, e);
            return null;
        } finally {
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }

2傳送json post請求

    private String sendPostByJson(String url, Map<String, Object> params,
            Map<String, String> headers) {
        CloseableHttpClient httpclient = httpClient.getHttpClient();
        HttpPost post = new HttpPost(url);
        if (params != null && !params.isEmpty()) {
            List<Header> tmpHeaders = new ArrayList<>();
            tmpHeaders.add(
                    new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType()));
            if (headers != null) {
                headers.keySet().stream().forEach(key -> {
                    Header header = new BasicHeader(key, headers.get(key));
                    tmpHeaders.add(header);
                });
            }
            post.setHeaders(tmpHeaders.toArray(new Header[] {}));
            String json = ObjectMapperUtils.toJSON(params);
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            post.setEntity(entity);
        }
        int timeout = (int) TimeUnit.MINUTES.toMillis(3);
        RequestConfig timeOutRequestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build();
        post.setConfig(timeOutRequestConfig);
        return execAndHandleThrowable(() -> {
            CloseableHttpResponse response = httpclient.execute(post);
            HttpEntity resEntity = response.getEntity();
            return EntityUtils.toString(resEntity, StandardCharsets.UTF_8);
        }, e -> logger.error(e.getMessage() + " when send json to server"));
    }

3,send form data post請求

    public String sendPostByFormData(String url, Map<String, Object> params,
            Map<String, String> headers) {
        CloseableHttpClient httpclient = httpClient.getHttpClient();
        HttpPost post = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        if (params != null) {
            params.keySet().stream().forEach(key -> {
                Object o = params.get(key);
                if (o != null) {
                    if (o instanceof File) {
                        File file = (File) o;
                        builder.addBinaryBody(key, file, ContentType.MULTIPART_FORM_DATA,
                                StringUtils.defaultString(file.getName()));
                    } else {
                        StringBody stringBody = new StringBody(o.toString(),
                            ContentType.MULTIPART_FORM_DATA);
                        builder.addPart(key, stringBody);
                    }
                }
            });
        }
        List<Header> tmpHeaders = new ArrayList<>();
        if (headers != null) {
            headers.keySet().stream().forEach(key -> {
                Header header = new BasicHeader(key, headers.get(key));
                tmpHeaders.add(header);
            });
        }
        post.setHeaders(tmpHeaders.toArray(new Header[] {}));
        HttpEntity fileEntry = builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).build();
        post.setEntity(fileEntry);
        int timeout = (int) TimeUnit.MINUTES.toMillis(KConfDefault.TEN);
        RequestConfig timeOutRequestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build();
        post.setConfig(timeOutRequestConfig);
        return execAndHandleThrowable(() -> {
            CloseableHttpResponse response = httpclient.execute(post);
            HttpEntity resEntity = response.getEntity();
            return EntityUtils.toString(resEntity, StandardCharsets.UTF_8);
        }, e -> logger.error(e.getMessage() + " when send form data"));
    }

4, 可以通過header判斷髮送哪個請求

    public String sendPost(String url, Map<String, Object> params, Map<String, String> headers) {
        if (StringUtils.isEmpty(url)) {
            return null;
        }
        if (checkMapKeyValueEqual(headers, "Content-Type",
                ContentType.APPLICATION_JSON.getMimeType())) {
            return sendPostByJson(url, params, headers);
        } else if (checkMapKeyValueEqual(headers, "Content-Type",
                ContentType.MULTIPART_FORM_DATA.getMimeType())) {
            return sendPostByFormData(url, params, headers);
        }
        return sendPostByCommon(url, params, headers);
    }

    private boolean checkMapKeyValueEqual(Map<String, String> map, String key, String value) {
        if (map == null || map.isEmpty()) {
            return false;
        }
        AtomicBoolean search = new AtomicBoolean(false);
        map.keySet().stream().forEach(tmpKey -> {
            if (!search.get() && StringUtils.equalsIgnoreCase(key, tmpKey)
                    && StringUtils.equalsIgnoreCase(value, map.get(tmpKey))) {
                search.set(true);
            }
        });
        return search.get();
    }

 

相關文章