Request

背景

学习记录一种请求方式

分析

逻辑:
	简单
代码量:
	偏多
维护:
	所有的请求用的都是同样的链接配置(超时时间,代理等等),如果有特殊的(一个/一批)请求还需要特殊处理,业务逻辑方法还需要该配置
Http请求方式有多种所以需要调用者选择使用哪种请求方式,也可以提供一些固定的方法例如 getRest / postRest / delRest ...
这里直接使用三个方法
	rest(入参) //用户调用的方法,根据自身业务逻辑增加参数,封装结果(根据业务逻辑封装结果数据,可以是JSON/XML ...)
	getRequest(); //初始化创建一个Request对象,添加数据(请求类型/请求路径/请求头/请求体),配置链接(超时时间)
	exec(); // 执行Request 获得Response对象,检验(返回的状态码),处理结果(将结果简单转换为String)

完整代码

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>fluent-hc</artifactId>
        </dependency>
package com.rs.testfield.rest;

import com.alibaba.fastjson.JSON;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.entity.ContentType;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;
import java.util.Map;

public class RequestClient {

    public String rest() {
        return exec(getRequest("get", "http://localhost:333/api/info", null, null));

    }


    private String exec(Request request) {
        if (request == null) {
            throw new RuntimeException("request is null");
        }
        try {
            Response response = request.execute();
            HttpResponse httpResponse = response.returnResponse();
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity == null) {
                return null;
            }
            String responseText = EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8);
            if (statusCode != 200) {
                throw new RuntimeException(statusCode + ":" + responseText);
            }
            return responseText;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private Request getRequest(String type, String url, Map<String, String> headers, Object body) {

        Request request;
        /**
         * 对 Body的处理
         */
        String bodyString = null;
        if (body != null) {
            bodyString = JSON.toJSONString(body);
        }


        switch (type) {
            case "GET":
                request = Request.Get(url);
                break;
            case "POST":
                request = Request.Post(url);
                if (StringUtils.isEmpty(bodyString)) {
                    request = request.bodyString(bodyString, ContentType.APPLICATION_JSON);
                }
                break;
            case "PUT":
                request = Request.Put(url);
                if (StringUtils.isEmpty(bodyString)) {
                    request = request.bodyString(bodyString, ContentType.APPLICATION_JSON);
                }
                break;
            case "DELETE":
                request = Request.Delete(url);
                break;
            case "PATCH":
                request = Request.Patch(url);
                if (StringUtils.isEmpty(bodyString)) {
                    request = request.bodyString(bodyString, ContentType.APPLICATION_JSON);
                }
                break;
            default:
                throw new RuntimeException("未知的http请求方法 type=" + type);
        }

        /**
         * 设置请求头
         */
        if (headers != null) {
            for (String key : headers.keySet()) {
                String value = headers.get(key);
                request.addHeader(key, value);
            }
        }

        /**
         * 对链接做一些配置 / 超时时间
         */
        request.connectTimeout(3000);
        request.socketTimeout(3000);

        /**
         * 设置代理
         */
        request.viaProxy(new HttpHost("192.168.0.0", 30));


        return request;

    }


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值