JAVA 利用org.springframework.http 发送HTTP 请求

            RestTemplate client = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity> requestEntity = new HttpEntity(requestBody, headers);
            ResponseEntity exchange = null;
            try{
                exchange = client.exchange(host+url, method, requestEntity, Object.class);
                System.out.println( "--------------requestBody-------------");         
                System.out.println(JSON.toJSONString(requestBody));             
                System.out.println( "-------------responseBody-------------");           
                System.out.println(JSON.toJSONString(exchange.getBody()));  
            }catch (HttpClientErrorException e){
                System.out.println( "--------------requestBody-------------");              
                System.out.println(JSON.toJSONString(requestBody));            
                System.out.println(e.getMessage());
                System.out.println(e.getStatusText());
                System.out.println( "-------------responseBody-------------");           
                System.out.println( e.getResponseBodyAsString());                
                e.printStackTrace();
            }catch (Exception e){
                System.out.println(e.getMessage());               
            } 
  

 

requestBody传进来Object 

依赖包为

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

 

 

你可能感兴趣的:(java,java)