http请求

/**
     * <p>
     * 发送https请求
     * </p>
     *
     * @author wumingfang
     * @date 2020年5月18日 上午10:27:03
     * @param code
     * @param message
     * @throws CodeException
     */
    protected String httpClientGet(String url) throws CodeException {
        StringBuilder result = new StringBuilder();
        String urlNameString = url;
        URLConnection connection = null;
        try {
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (Entry<String, List<String>> entry : map.entrySet()) {
                LOGGER.info(LogType.INFO,"Key = " + entry.getKey() + ", Value = " + entry.getValue());
            }
            
        } catch (Exception e) {
            LOGGER.error(LogType.ERROR, e.getMessage(), e);
            throw new CodeException(e.getMessage());
        }
      
        try(BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {            
            // 定义 BufferedReader输入流来读取URL的响应
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            LOGGER.error(LogType.ERROR, e.getMessage(), e);
            throw new CodeException("httpGet请求异常" + e.getMessage());
        }
        return result.toString();
    }
    
    /**
     * <p>Description https Post请求</p>
     * @author wumf
     * @date 2020年5月18日 下午3:53:31
     * @param url
     * @param headerMap
     * @return
     * @throws CodeException
     */
    protected String httpClientPost(String url, Map<String, String> headerMap) throws CodeException {
        //封装请求参数
        String postResult = "";
        HttpPost httpPost = new HttpPost(url);
        if(headerMap != null && headerMap.size() > 0) {
            Set<Map.Entry<String,String>> entrySet = headerMap.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        try(CloseableHttpClient httpClient = HttpClients.createDefault()) {                        
            CloseableHttpResponse response = httpClient.execute(httpPost);
            postResult = EntityUtils.toString(response.getEntity(),"UTF-8");
            
        } catch (Exception e) {
            LOGGER.error(LogType.ERROR, e.getMessage(), e);
            throw new CodeException("httpPost请求异常" + e.getMessage());
        }
        
        return postResult;
    }
    
    /**
     * <p>Description https Post请求</p>
     * @author wumf
     * @date 2020年5月18日 下午3:53:31
     * @param url
     * @param headerMap
     * @return
     * @throws CodeException
     */
    protected String httpClientPostJson(String url, JSONObject param) throws CodeException {
        //封装请求参数
        URLConnection conn = null;
        StringBuilder result = new StringBuilder();
        try {                     
            URL realUrl = new URL(url);            
            // 打开和URL之间的连接
            conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");    
            conn.setRequestProperty("Content-Type", "application/json");// 设置发送数据的格式
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
        } catch (Exception e) {
            LOGGER.error(LogType.ERROR, e.getMessage(), e);
            throw new CodeException(e.getMessage());
        }
        
        // 获取URLConnection对象对应的输出流
        try(PrintWriter out = new PrintWriter(conn.getOutputStream())) {
            // 发送请求参数
            out.print(param);
            out.flush();
        } catch (Exception e) {
            LOGGER.error(LogType.ERROR, e.getMessage(), e);
            throw new CodeException(e.getMessage());
        }
        
        try(BufferedReader in = new BufferedReader(
                new InputStreamReader(conn.getInputStream()))) {
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            LOGGER.error(LogType.ERROR, e.getMessage(), e);
            throw new CodeException(e.getMessage());
        }    
        return result.toString();
    }

 

 

package cpcn.dsp.xyrchannel.api.rpc.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.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;

import cpcn.dsp.tool.middleware.log.LogType;
import cpcn.dsp.tool.middleware.log.Loggerx;
import cpcn.dsp.tool.system.CodeException;
import cpcn.dsp.xyrchannel.api.rpc.constans.XYRChannelConstants;

/**
 * <pre>
 * Modify Information:湘信融http请求公共类
 * Author       Date          Description
 * ============ ============= ============================
 * wumf      2020年5月19日       create this file
 * </pre>
 */
public final class HttpClientUtil {

    private HttpClientUtil (){
        throw new IllegalStateException("Utility class");
    }
    
    private static final Loggerx LOGGER = Loggerx.getLogger("system");
    
    /**
     * <p>Description http请求,get类型</p>
     * @author wumf
     * @date 2020年5月19日 上午11:25:06
     * @param url
     * @param jsonParams
     * @return
     * @throws CodeException
     */
    public static String httpClientGet(String url) throws CodeException {
        String httpResponse = "";
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(url);
        try {
            get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
            get.addHeader("accept", "*/*");
            get.addHeader("connection", "Keep-Alive");
            LOGGER.info(LogType.INFO, "请求地址"+url);
            CloseableHttpResponse closeResponse = client.execute(get);
            HttpEntity entity = closeResponse.getEntity();
            httpResponse = EntityUtils.toString(entity);
            LOGGER.info(LogType.INFO, "响应内容"+httpResponse);
        } catch (Exception e) {
            LOGGER.error(LogType.ERROR, "与服务端通信异常" + e.getMessage(), e);
            throw new CodeException(XYRChannelConstants.ERROR_CODE_5000, XYRChannelConstants.ERROR_MESSAGE_5000, e);
        }
        return httpResponse;
    }
    
    
    /**
     * <p>Description http请求,post类型</p>
     * @author wumf
     * @date 2020年5月19日 上午11:25:06
     * @param url
     * @param jsonParams
     * @return
     * @throws CodeException
     */
    public static String httpClientPostJson(String url, JSONObject jsonParams) throws CodeException {
        String httpResponse = "";
        try {
            CloseableHttpClient client = HttpClientBuilder.create().build();
            HttpPost post = new HttpPost(url);
            LOGGER.info(LogType.INFO, "请求地址"+url+",传递参数"+jsonParams.toJSONString());
            StringEntity entity = new StringEntity(jsonParams.toJSONString(), "UTF-8");
            post.setEntity(entity);
            post.setHeader("Content-Type", "application/json;charset=utf8");
            CloseableHttpResponse response = client.execute(post);
            HttpEntity responseEntity = response.getEntity();
            if(responseEntity != null) {
                httpResponse = EntityUtils.toString(response.getEntity());
                LOGGER.info(LogType.INFO, "响应内容"+httpResponse);
            }            
        } catch (Exception e) {
            LOGGER.error(LogType.ERROR, "与服务端通信异常"+e.getMessage(),e);
            throw new CodeException(XYRChannelConstants.ERROR_CODE_5000, XYRChannelConstants.ERROR_MESSAGE_5000, e);
        }       
        
        return httpResponse;
    }
    
    
    
    
    
}

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wmf_helloWorld

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值