LoadController.java 2.54 KB
package com.viontech.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.viontech.model.LoadEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: zhuhai
 * Date: 2023-04-04
 * Time: 14:24
 */
@RestController
@Slf4j
public class LoadController {

    @Resource
    private RestTemplate restTemplate;


    @PostMapping({"/load"})
    public Object load(@RequestBody LoadEntity loadEntity, @RequestHeader(required = false,name = "Authorization") String authorization) throws JsonProcessingException {
        String url = loadEntity.getUrl();
        String param = loadEntity.getParam();
        HttpMethod method = loadEntity.getMethod();
        HttpHeaders headers = new HttpHeaders();
        headers.set("app-code", "");
        if (authorization != null) {
            headers.set("Authorization", authorization);
        }

        if (!method.equals(HttpMethod.GET)) {
            headers.setContentType(MediaType.APPLICATION_JSON);
        } else if (param != null) {
            HashMap<String, Object> hashMap = JSON.parseObject(param, HashMap.class);
            StringBuilder sb = (new StringBuilder(url)).append("?");
            Iterator iterator = hashMap.entrySet().iterator();

            while(iterator.hasNext()) {
                Map.Entry<String, Object> entry = (Map.Entry<String, Object>) iterator.next();
                sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
            }
            url = sb.toString().replaceFirst("&", "");
        }

        log.info("url : [{}]", url);
        HttpEntity<Object> entity = new HttpEntity(param, headers);
        ResponseEntity<Object> exchange = this.restTemplate.exchange(url, method, entity, Object.class, new Object[0]);
        return exchange.getBody();
    }

}