發送http請求,使用httpClient或者okHttpClient都非常好用,直接集成就可以使用,在Springboot中,發送http請求還可以選擇Springboot內置的RestTemplate類,可以直接發送http請求,不用加入其他依賴,開箱即用
一、自動注入RestTemplate並配置
-
添加pom依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
-
第一種方式
@Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory(){ SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setReadTimeout(30000); // 單位爲ms factory.setConnectTimeout(30000); // 單位爲ms return factory; } @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory){ return new RestTemplate(factory); }
-
第二種方式
@Autowired private RestTemplateBuilder builder; //使用RestTemplateBuilder來實例化RestTemplate對象,spring默認已經注入了RestTemplateBuilder實例 @Bean public RestTemplate restTemplate() { builder.setConnectTimeout(60 * 1000) .setReadTimeout(60 * 1000); return builder.build(); }
二、使用
RestTemplate調用方法
// 直接注入
@Autowired
private RestTemplate restTemplate;
//1.直接獲取響內容
String object = restTemplate.getForObject("http://localhost:8080/getString?src=hello", String.class);
//2.獲取響應信息,包含響應狀態、響應頭、響應內容
ResponseEntity<String> entity = restTemplate.getForEntity("http://localhost:8080/getString?src=hello", String.class);
// post請求
User user = restTemplate.postForObject("http://localhost:8080/getUser", postData, User.class);
// 設置請求頭
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Content-Type", "application/json;charset=utf-8");
//設置請求參數
Map<String, Object> postData = new HashMap<>();
postData.put("id", 1L);
postData.put("name", "測試");
postData.put("age", 18);
//將請求頭和請求參數設置到HttpEntity中
HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(postData, httpHeaders);
User user = restTemplate.postForObject("http://localhost:8080/getUser", httpEntity, User.class);
// 使用exchange()方法
exchange():在URL上執行特定的HTTP方法,返回包含對象的ResponseEntity,這個對象是從響應體中映射得到的
String strbody=restTemplate.exchange(uri, HttpMethod.GET, entity,String.class).getBody();
、WeatherResponse weatherResponse= JSONObject.parseObject(strbody,WeatherResponse.class);
-
delete():這個方法是在特定的URL上對資源執行HTTP DELETE操作
-
exchange():在URL上執行特定的HTTP方法,返回包含對象的ResponseEntity,這個對象是從響應體中映射得到的
-
execute() 在URL上執行特定的HTTP方法,返回一個從響應體映射得到的對象
-
getForEntity() 發送一個HTTP GET請求,返回的ResponseEntity包含了響應體所映射成的對象
-
getForObject() 發送一個HTTP GET請求,返回的請求體將映射爲一個對象
-
postForEntity() ``POST 數據到一個URL,返回包含一個對象的ResponseEntity,這個對象是從響應體中映射得到的
-
postForObject() POST數據到一個URL,返回根據響應體匹配形成的對象
-
headForHeaders() 發送HTTP HEAD請求,返回包含特定資源URL的HTTP頭
-
optionsForAllow() 發送HTTP OPTIONS請求,返回對特定URL的Allow頭信息
-
postForLocation() POST 數據到一個URL,返回新創建資源的URL
-
put() PUT 資源到特定的URL
解決中文亂碼:
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);