Springboot之http调用篇

get调用

try {
            HashMap<String, String> params = new HashMap<>();
            params.put("act", "login");

            String httpEntity = HttpUtil.sendGetRequestString ("http://cd.luozhen.top/api.php", params);

            System.out.print (httpEntity);
            HashMap<String, Object> result = new HashMap<>();
            result.put("lists", "2222");
            result.put("data", JSONObject.fromObject(httpEntity));
            return PageResultHelper.ok(result);
        } catch (Exception e) {
            e.printStackTrace();

            return PageResultHelper.error (e.getMessage());
            //log.error("GET请求异常:{}", e.getMessage());
        }

HhtpUtil.java

package com.gaodun.agencyregist.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author: wpp
 * @Date: 2019/11/12 14:15
 */
@Slf4j
public class HttpUtil {
    public static HttpEntity sendGetRequest(String url, Map<String, String> params) throws Exception {
        final StringBuffer tmp = new StringBuffer(url);
        if (ObjectUtil.isNotEmpty(params)) {
            Set<Map.Entry<String, String>> paramSet = params.entrySet();
            if (paramSet.size() > 0) {
                tmp.append("?");
                int totalLen = paramSet.size(), index = 0;
                for (Map.Entry<String, String> entry : paramSet) {
                    tmp.append(entry.getKey() + "=" + entry.getValue());
                    if (++index < totalLen) {
                        tmp.append("&");
                    }
                }
            }
            log.info("Get params:" + params.toString());
        }
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(tmp.toString());
        HttpResponse response = httpClient.execute(httpGet);
        return response.getEntity();
    }

    public static String sendGetRequestString(String url) {
        try {
            HttpEntity entity = sendGetRequest(url, null);
            return entityToString(entity);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("GET请求异常:{}", e.getMessage());
        }
        return "";
    }

    public static String sendGetRequestString(String url, Map<String, String> params) {
        try {
            HttpEntity entity = sendGetRequest(url, params);
            return entityToString(entity);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("GET请求异常:" + e.getMessage());
        }
        return "";
    }

    public static String entityToString(HttpEntity entity) throws Exception {
        return entity == null ? null : EntityUtils.toString(entity, "utf-8");
    }

    /**
     * 发送POST请求
     *
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static HttpEntity sendPostRequest(String url, Map<String, String> params) throws Exception {
        HttpClient httpClient = HttpClients.createDefault();
        List<NameValuePair> listParams = new ArrayList<NameValuePair>();
        if (params != null) {
            Set<Map.Entry<String, String>> set = params.entrySet();
            for (Map.Entry<String, String> entry : set) {
                listParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        log.info("Post params:" + listParams.toString());
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(listParams, "utf-8"));
        HttpResponse reponse = httpClient.execute(httpPost);
        return reponse.getEntity();
    }

    public static String sendPostRequestString(String url, Map<String, String> params) {
        HttpEntity entity;
        try {
            entity = sendPostRequest(url, params);
            return entityToString(entity);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("POST请求异常:" + e.getMessage());
        }
        return "";
    }

    public static String sendPostRequestString(String url, String param) {
        HttpEntity entity;
        HttpClient httpClient = HttpClients.createDefault();
        try {
            log.info("Post params:" + param);
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new StringEntity(param, "utf-8"));
            HttpResponse reponse = httpClient.execute(httpPost);
            entity = reponse.getEntity();
            return entityToString(entity);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("POST请求异常:" + e.getMessage());
        }
        return "";
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值