Spring RestfulTemplate json POST 요청 보 내기

11844 단어 Java
코드
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;


//   JSON    
@Value("classpath:query.json")
    private Resource query;

//   JSON    
private JSONObject readJson() {
        JSONObject jsonObject = new JSONObject();
        try {
            String json = IOUtils.toString(query.getInputStream(), Charset.forName("UTF-8"));
            jsonObject = JSONObject.parseObject(json);
        } catch (IOException e) {
            e.printStackTrace();

        }
        return jsonObject;
    }

//   POST   
public String post() {
        String uri = "http://" + URL + PARAMS;

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<String>(readJson().toJSONString(), headers);

        String response = restTemplate.postForObject(
                uri, entity, String.class);

        return response;
    }

pom.xml
<dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.61version>
        dependency>
  <dependency>
            <groupId>commons-iogroupId>
            <artifactId>commons-ioartifactId>
            <version>2.6version>
        dependency>

좋은 웹페이지 즐겨찾기