HttpUtils请求工具类

package com.rc.openapi.util;


import com.alibaba.nacos.client.identify.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
    private static final String SAP_USERNAME = InfoUtil.getInstance().getInfo("config", "sap_username");
    private static final String SAP_PASSWORD = InfoUtil.getInstance().getInfo("config", "sap_password");

    public static Map<String, String> sendDataAndGetResult(String url,
                                                     String body) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        Map<String, String> resultMap = new HashMap<>(4);
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(75000).setConnectTimeout(45000).build();//设置请求和传输超时时间
//            String loginKey = doms_stock_username + ":" + doms_stock_password;
//            byte[] tokenByte = Base64.encodeBase64(loginKey.getBytes());
//            String tokenStr = new String(tokenByte);
//            httpPost.setHeader("Authorization", "Basic " + tokenStr);
//            httpPost.setHeader("Authorization", "Basic " + Base64.encodeBase64("PO_CONN:POPassw0rd".getBytes()));
            httpPost.setConfig(requestConfig);
            CloseableHttpResponse response = null;
            String result = null;
            try {
                if (body == null) {
                    // pass
                } else {
                    StringEntity entity = new StringEntity(body, "UTF-8");
                    entity.setContentEncoding("UTF-8");
                    entity.setContentType("application/json");
                    httpPost.setEntity(entity);
                }
                response = httpClient.execute(httpPost);
                StatusLine statusLine = response.getStatusLine();
                int statusCode = statusLine.getStatusCode();
                logger.info(String.format("http protocol:%s statusCode:%s reasonPhrase:%s", new Object[]{statusLine.getProtocolVersion(), statusCode, statusLine.getReasonPhrase()}));
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, Consts.UTF_8);
                if (statusCode == 202 || statusCode == 204) {
                    statusCode = 200;
                }
                resultMap.put("httpCode", String.valueOf(statusCode));
                resultMap.put("result", result);
            } catch (UnsupportedEncodingException e) {
                throw new HttpClientRuntimeException("httpClient post request error", e);
            } catch (IOException e) {
                e.printStackTrace();
                resultMap.put("httpCode", "ERROR");
                resultMap.put("result", null);
            } finally {
                try {
                    if (response != null) {
                        response.close();
                    }
                } catch (IOException e) {
                    throw new HttpClientRuntimeException("httpClient post request error", e);
                }
            }
            logger.info(String.format("post request url is %s, body is %s, response data is \n%s", url, body, result));
            return resultMap;

        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                throw new HttpClientRuntimeException("httpClient post request error", e);
            }
        }


    }

    public static String postBody(String url, String body) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(75000).setConnectTimeout(45000).build();//设置请求和传输超时时间
            String loginKey = SAP_USERNAME + ":" + SAP_PASSWORD;
            byte[] tokenByte = Base64.encodeBase64(loginKey.getBytes());
            String tokenStr = new String(tokenByte);
            httpPost.setHeader("Authorization", "Basic " + tokenStr);
            httpPost.setConfig(requestConfig);
            CloseableHttpResponse response = null;
            String result = null;
            try {
                if (body == null) {
                    // pass
                } else {
                    StringEntity entity = new StringEntity(body, "UTF-8");
                    entity.setContentEncoding("UTF-8");
                    entity.setContentType("application/json");
                    httpPost.setEntity(entity);
                }
                response = httpClient.execute(httpPost);
                StatusLine statusLine = response.getStatusLine();
                logger.info(String.format("http protocol:%s statusCode:%s reasonPhrase:%s", new Object[]{statusLine.getProtocolVersion(), statusLine.getStatusCode(), statusLine.getReasonPhrase()}));
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, Consts.UTF_8);
            } catch (UnsupportedEncodingException e) {
                throw new HttpClientRuntimeException("httpClient post request error", e);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (response != null) {
                        response.close();
                    }
                } catch (IOException e) {
                    throw new HttpClientRuntimeException("httpClient post request error", e);
                }
            }
            logger.info(String.format("post request url is %s, body is %s, response data is \n%s", url, body, result));
            return result == null ? "" : result.trim();

        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                throw new HttpClientRuntimeException("httpClient post request error", e);
            }
        }
    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值