HttpUtil.java 1.99 KB
package com.meishu.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * http请求
 */
public class HttpUtil {

    /**
     * GET 请求
     * @param params
     * @param url
     * @return
     */
    public static JSONObject get(Map<String, Object> params, String url) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, params);
        String body = responseEntity.getBody();
        JSONObject object = JSON.parseObject(body);
        return object;
    }

    /**
     * POST 请求
     * @param params
     * @param url
     * @return
     */
    public static JSONObject post(Map<String, Object> params, String url) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, params, String.class);
        String body = responseEntity.getBody();
        JSONObject object = JSON.parseObject(body);
        return object;
    }

    /**
     * POST 请求 带Token
     *
     * @param param
     * @param token
     * @param url
     * @return
     */
    public static JSONObject sendPost(Map<String, Object> param, String token, String url, Object obj) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Accept", MediaType.ALL_VALUE);
        headers.add("Authorization", "Bearer " + token);
        HttpEntity<String> formEntity = new HttpEntity<String>(param.toString(), headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, formEntity, String.class, obj);
        String body = responseEntity.getBody();
        JSONObject object = JSON.parseObject(body);
        return object;
    }
}