package com.bailuntec.util;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 网络请求工具类
 */
public class HttpUtil {
    public static RestTemplate restTemplate = new RestTemplate();
    /**
     * 设置跨域请求头
     * @param response
     * @param request
     */
    public static void setCors(HttpServletResponse response, HttpServletRequest request) {
        String origin = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", origin);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE");
        response.setHeader("Access-Control-Allow-Credentials", "true");
    }

    /**
     * 发起http get请求
     * @param url
     * @return
     * @throws Exception
     */
    public static String httpGet(String url) throws Exception{
        return restTemplate.getForObject(url, String.class);
    }

    /**
     * 发起http post请求
     * @param url
     * @param paramsJson
     * @return
     * @throws Exception
     */
    public static String httpPost(String url, String paramsJson) throws Exception{
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        HttpEntity<String> requestEntity = new HttpEntity<>(paramsJson, headers);
        return restTemplate.postForObject(url, requestEntity, String.class);
    }




}