get通过发送Body传参-工具类

本文介绍了如何在Java中通过构建HTTPGET请求,包括URL参数替换、请求体的组装,使用Gson进行JSON数据解析,以及使用自定义工具类处理连接超时和异常情况的过程。
摘要由CSDN通过智能技术生成

1、调用方式


String url ="http://ip/xxx/zh/xxxxx/xxxx/userCode";
//进行url中的对应的参数
url2 =url2.replace("ip",bancirili);
url2 =url2.replace("zh",zh);
url2 = url2.replace("userCode",userCode);

String dateTime = xxxx;
//组装请求体
String requestBody = "{\"urlParams\":\"?$dateTime=" + dateTime + "\"}";
//get-发送带body的请求
Map<String, String> stringStringMap = HttpClientUtils.httpGet(url, requestBody);

//获取请求到的数据,当前为json
String body = stringStringMap.get("body");

//使用Gson将响应数据转换为实体对象
Gson gson = new Gson();
//MqShiftResponse为JSON结构,
//例如 code,msg,List<MqShift>,此处从MqShiftResponse 解析出MqShift存至List
MqShiftResponse responseData = gson.fromJson(body,MqShiftResponse.class);
List<MqShift> shiftList = responseData.getData();

有公司自己的工具类(json转为实体)解析也可以

2、工具类(get发送Body传参-工具类)

public static Map<String, String> httpGet(String url, String requestBody) {
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000) // 设置连接超时时间为5秒
                .setSocketTimeout(5000) // 设置请求超时时间为5秒
                .build();

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        httpPost.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));

        Map<String, String> resultMap = new HashMap<>();
        try {
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            String body = null;
            int status = 400;

            status = httpResponse.getStatusLine().getStatusCode();
            if (null != httpEntity) {
                body = EntityUtils.toString(httpEntity);
            }

            resultMap.put("status", String.valueOf(status));
            resultMap.put("body", body);

        } catch (ClientProtocolException e) {
            e.printStackTrace();
            log.error("发送请求失败", e);
            throw new RuntimeException("发送请求失败", e);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("IO异常", e);
            throw new RuntimeException("IO异常", e);
        } finally {
            try {
                //关闭流,释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultMap;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值