Java中Http请求restful接口POST、GET、PUT、DELETE等

本文介绍springboot中使用CloseableHttpClient类创建http连接

// 创建连接与设置连接参数
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

 直接上代码实现:

url为服务地址;map为请求参数;

后面有方法介绍

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
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 org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: zhouzihan
 */
@Component
@Slf4j
public class HttpComponentsClient {
    static String resultData = null;

    /**
     * 调用服务端的POST请求
     * 服务端入参注解:     @RequestBody
     *
     * @param postUrl 设备服务请求地址
     * @param map     设备对象参数<k,v>
     * @throws Exception
     */
    public static String doPost(String postUrl, Map<String, Object> map) throws Exception {
        // 请求参数
        String json = JSON.toJSONString(map);
        // 创建连接与设置连接参数
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(postUrl);
        StringEntity entity = new StringEntity(json);
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        // 发起请求与接收返回值
        HttpResponse response = httpClient.execute(httpPost);
        resultData = returnResult(response);
        httpClient.close();
        return resultData;
    }

    /**
     * 调用服务端的GET请求
     * 服务端入参注解: @RequestParam
     *
     * @param getUrl 设备服务请求地址
     * @param map    (支持单个、多个参数拼接)
     *               key:参数名称
     *               value:参数值
     * @return resultData
     * @throws Exception
     */
    public static String doGetRequestParam(String getUrl, Map<String, Object> map) throws Exception {
        String obj = questionMarksTheParticipation(map);
        getUrl = getUrl + obj;
        // 创建连接与设置连接参数
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(getUrl);
        // 发起请求与接收返回值
        HttpResponse response = httpClient.execute(httpGet);
        resultData = returnResult(response);
        httpClient.close();
        return resultData;
    }

    /**
     * 调用服务端的GET请求
     * 服务端入参注解: @PathVariable
     */
    public static String doGetPathVariable(String getUrl, Object val) throws Exception {
        //入参有中文需要编码
        getUrl = getUrl + val;
        // 创建连接与设置连接参数
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(getUrl);
        // 发起请求与接收返回值
        HttpResponse response = httpClient.execute(httpGet);
        resultData = returnResult(response);
        httpClient.close();
        return resultData;
    }

    /**
     * 调用服务端的PUT请求
     *
     * @param map (支持单个、多个参数拼接)
     *            *          key:参数名称
     *            *          value:参数值
     */
    public static String doPut(String getUrl, Map<String, Object> map) throws Exception {
        //入参有中文需要编码
        String obj = questionMarksTheParticipation(map);
        getUrl = getUrl + obj;
        // 创建连接与设置连接参数
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPut httpPut = new HttpPut(getUrl);
        // 发起请求与接收返回值
        HttpResponse response = httpClient.execute(httpPut);
        resultData = returnResult(response);
        httpClient.close();
        return resultData;
    }

    /**
     * 调用服务端的DELETE请求
     *
     * @param map (支持单个、多个参数拼接)
     *            *          key:参数名称
     *            *          value:参数值
     */
    public static String doDelete(String getUrl, Map<String, Object> map) throws Exception {
        //入参有中文需要编码
        String obj = questionMarksTheParticipation(map);
        getUrl = getUrl + obj;
        // 创建连接与设置连接参数
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpDelete httpDelete = new HttpDelete(getUrl);
        // 发起请求与接收返回值
        HttpResponse response = httpClient.execute(httpDelete);
        resultData = returnResult(response);
        httpClient.close();
        return resultData;
    }


    /**
     * questionMarksTheParticipation():问号传参
     *
     * @param map key、value拼接  key或value存在空值跳过拼接
     *            例:key=projectId
     *            value=1
     *            参数拼接结果:  ?projectId=1
     * @return obj
     */
    public static String questionMarksTheParticipation(Map<String, Object> map) throws UnsupportedEncodingException {
        StringBuilder obj = new StringBuilder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (null != entry.getKey() && null != entry.getValue()) {
                if (!entry.getKey().isEmpty()) {
                    String s = entry.getKey() + "=" + URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8");
                    obj.append(s).append("&");
                }
            }
        }
        obj = new StringBuilder("?" + obj.substring(0, obj.length() - 1));
        return obj.toString();
    }

    public static String returnResult(HttpResponse response) throws IOException {
        if (response.getStatusLine().getStatusCode() != 200) {
            log.error("调用服务端异常.");
        }
        HttpEntity res = response.getEntity();
        String resultData = EntityUtils.toString(res);
        log.info("从服务端返回结果: " + resultData);
        return resultData;
    }
}

注意:所有的方法传递参数的方式都是Map<String,Object>,这样做不需要关注外面对象的具体属性、参数属性个数。

直接把参数put到map中,在上面类中最后的两个方法questionMarksTheParticipation()和returnResult()已经将GET、PUT和DELETE请求参数做拼接处理,拼接到请求URL中了

/**
     * questionMarksTheParticipation():问号传参
     *
     * @param map key、value拼接  key或value存在空值跳过拼接
     *            例:key=projectId
     *            value=1
     *            参数拼接结果:  ?projectId=1
     * @return obj
     */
    public static String questionMarksTheParticipation(Map<String, Object> map) throws UnsupportedEncodingException {
        StringBuilder obj = new StringBuilder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (null != entry.getKey() && null != entry.getValue()) {
                if (!entry.getKey().isEmpty()) {
                    String s = entry.getKey() + "=" + URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8");
                    obj.append(s).append("&");
                }
            }
        }
        obj = new StringBuilder("?" + obj.substring(0, obj.length() - 1));
        return obj.toString();
    }

    public static String returnResult(HttpResponse response) throws IOException {
        if (response.getStatusLine().getStatusCode() != 200) {
            log.error("调用服务端异常.");
        }
        HttpEntity res = response.getEntity();
        String resultData = EntityUtils.toString(res);
        log.info("从服务端返回结果: " + resultData);
        return resultData;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

憨子周

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

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

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

打赏作者

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

抵扣说明:

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

余额充值