Java使用HttpClient实现GET和POST请求

发布时间 2023-11-17 18:41:03作者: 马铃薯1

GET请求(带参数)

前端

export const getRealTimeData = (deviceLabel) => {
  return request({
    url: '/blade-inorganization/Data/realTime-data?deviceLabel='+deviceLabel,
    method: 'get',
  })
}

import {getRealTimeData} from "@/api/inorganization/onlinestatistics/Pollution";

var devicelabel = "TSPXXZGLTB0054";
getRealTimeData0(devicelabel).then(res => {
    console.log('res', res);
})

后端

@GetMapping("/realTime-data")
@ApiOperationSupport(order = 3)
@ApiOperation(value = "获取历史数据", notes = "获取历史数据")
public String getRealTimeData(@RequestParam String deviceLabel){
    String Url="http://192.1.27.110:32672/api/data/device-detail/real-data-prop?deviceLabel=";
    try {
        // 传入参数
        String realUrl = Url + deviceLabel;
        System.out.println(realUrl);
        URL url = new URL(realUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 在连接之前设置属性
        // Content-Type实体头用于向接收方指示实体的介质类型,指定HEAD方法送到接收方的实体介质类型,或GET方法发送的请求介质类型
        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        // 设置打开与此URLConnection引用的资源的通信链接时使用的指定超时值(以毫秒为单位)
        conn.setConnectTimeout(10000);
        // 将读取超时设置为指定的超时时间,以毫秒为单位。
        // conn.setReadTimeout(60000);
        conn.setRequestMethod("GET");
        // Post 请求不能使用缓存
        conn.setUseCaches(false);

        // 建立连接
        conn.connect();
        // 获取响应
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        String result = "";
        while ((line = reader.readLine()) != null) {
            result += line;
        }
        reader.close();
        conn.disconnect();
        System.out.println(result);
        return result;
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (SocketTimeoutException e) {
        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }
    return null;
}

 

POST请求

前端

export const getHistoryData = (device) => {
  return request({
    url: '/blade-inorganization/Data/history-data',
    method: 'post',
    data: device
  })
}

import {getHistoryData} from "@/api/inorganization/onlinestatistics/Pollution";

var searchList = {
    "deviceCode": "A-A2-A1-A-001",
    "endTime": 1700031600000,
    "propList": [],
    "startTime": 1700024400000,
    "timeSpace": 1
};

getHistoryData(searchList).then(res => {
    console.log("++++++++++++++++++")
    console.log('res', res);
})

后端

@PostMapping("/history-data")
@ApiOperationSupport(order = 1)
@ApiOperation(value = "获取历史数据", notes = "获取历史数据")
public String getHistoryData(@RequestBody HashMap<String,Object> map){
    String url="http://192.1.27.110:32672/api/data/history-data/get-property-history-avg";
    HttpPost post = new HttpPost(url);
    String paramStr = JSON.toJSONString(map);
    StringEntity stringEntity = new StringEntity(paramStr, StandardCharsets.UTF_8);
    System.out.println(map);
    System.out.println(paramStr);
    //请求参数
    post.setEntity(stringEntity);

    //请求头
    post.setHeader("Content-Type", "application/json;charset=UTF-8");
    String msg = null;
    InetAddress ipaddr;
    try {
        //设置长/短连接 此处为短连接
        post.setHeader(HttpHeaders.CONNECTION, HTTP.CONN_CLOSE);

        //通过hostname获取本机ip地址
        ipaddr = InetAddress.getLocalHost();
        post.addHeader(new BasicHeader("API-RemoteIP", ipaddr.getHostAddress()));

        //创建httpclient对象发送post请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse resp = httpClient.execute(post);

        try {
            //返回信息
            HttpEntity entity = resp.getEntity();

            //获取请求状态码
            int statusCode = resp.getStatusLine().getStatusCode();
            if (entity != null) {
                msg = EntityUtils.toString(entity);
                System.out.println(msg);

                //输出日志
                //logger.info("url:" + url + "参数:" + params.toString() + "返回信息:" + msg);
            }
            if (statusCode != 200 && statusCode != 302) {
                //输出日志
                System.out.println(msg);
                //logger.info("url:" + url + "失败信息:" + msg);
            }
        } finally {
            resp.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        post.reset();
        post.releaseConnection();
    }
    return msg;
}