Java sends http request interface-RestTemplate

Spring-Send Http request-RestTemplate

RestTemplate is the core class used by Spring to synchronize the client. It simplifies communication with the http service, unifies the RESTFul standard, and encapsulates the http connection. We only need to pass in the url and its return value type. Compared with the previously commonly used HttpClient, RestTemplate is a more elegant way to call RESTFul services.

1.Maven introduction

pom.xml configuration items

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-web</artifactId>
	<version>5.3.22</version>
</dependency>

2.Code display

Send request tool class



import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;

public class HttpUtil {
    
    
    RestTemplate restTemplate = null;

    @PostConstruct
    public void before() {
    
    
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        //设置连接超时时间
        requestFactory.setConnectTimeout(10000);
        //设置读取超时时间
        requestFactory.setReadTimeout(10000);
        restTemplate = new RestTemplate(requestFactory);
    }


 	//post请求
    public JSONObject doPostForm(String urlPath, Map<String,String> body) {
    
    
        //  一定要设置header
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<?> request = new HttpEntity<Object>(bodyObject, headers);
        ResponseEntity<String> entity = restTemplate.postForEntity(urlPath, request, String.class);
        return JSONObject.parseObject(entity.getBody());
    }
    
	//Get请求
    public String doGetString(String urlPath) {
    
    
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<String> entity = new HttpEntity<>(headers);
        ResponseEntity<String> exchange = restTemplate.exchange(urlPath, HttpMethod.GET, entity, String.class);
        return exchange.getBody();
    }

}

Guess you like

Origin blog.csdn.net/icemeco/article/details/129138476