Spring HTTP Client

前端 未结 3 985
我在风中等你
我在风中等你 2021-01-31 02:11

I am new to Spring and I need my Java app to connect to another API over HTTP (JSON, RESTful). Does the Spring Framework have anything like a JSON HTTP Rest Client? What do Spri

3条回答
  •  遇见更好的自我
    2021-01-31 02:42

    i did it in following way :

    import java.io.FileReader;
    import java.util.HashMap;
    import java.util.Map;
    
    import org.json.simple.JSONObject;
    import org.json.simple.parser.JSONParser;
    import org.springframework.http.HttpEntity;
    import org.springframework.http.ResponseEntity;
    import org.springframework.http.converter.StringHttpMessageConverter;
    import org.springframework.util.LinkedMultiValueMap;
    import org.springframework.util.MultiValueMap;
    import org.springframework.web.client.RestTemplate;
    
    public class PostRequestMain {
    
        /**
         * POST with Headers call using Spring RestTemplate
         * 
         * 
         * @param args
         */
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            MultiValueMap headers = new LinkedMultiValueMap();
            Map map = new HashMap();
            map.put("Content-Type", "application/json");
            headers.setAll(map);
            Map req_payload = new HashMap();
            req_payload.put("name", "piyush");
    
            HttpEntity request = new HttpEntity<>(req_payload, headers);
            String url = "http://localhost:8080/portal-name/module-name/";
    
            // Create a new RestTemplate instance
            RestTemplate restTemplate = new RestTemplate();
    
            // Add the String message converter
            restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    
    
            ResponseEntity response = restTemplate.postForEntity(url, request, String.class);
    
    
            System.out.println(response);
    
        }
    
        private static void getPayloadMap() {
            JSONParser parser = new JSONParser();
    
            try {
    
                Object obj = parser.parse(new FileReader("C:\\Piyush\\test.json"));
                JSONObject jsonObject = (JSONObject) obj;
    
                Map payLoadMap = new HashMap();
                payLoadMap.putAll(jsonObject);
    
                System.out.println(jsonObject);
            } catch (Exception e) {
            }
        }
    
    }
    

提交回复
热议问题