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

get通过发送Body传参-工具类_第1张图片

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 stringStringMap = HttpClientUtils.httpGet(url, requestBody);

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

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

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

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

public static Map 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 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;
    }

你可能感兴趣的:(java,开发语言)