国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

SpringBoot中RestTemplate的使用備忘

這篇具有很好參考價(jià)值的文章主要介紹了SpringBoot中RestTemplate的使用備忘。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

SpringBoot中RestTemplate的使用備忘

1. 基本介紹

1,什么是 RestTemplate?1RestTemplateSpring 提供的用于訪問 Rest 服務(wù)的客戶端,RestTemplate 提供了多種可以便捷訪問遠(yuǎn)程 Http 服務(wù)的方法,能夠大大提高客戶端的編寫效率。

			RestTemplateSpring3 中引入的同步阻塞式 HTTP 客戶端。根據(jù) Spring 官方文檔介紹,在將來(lái)的版本中它可能會(huì)被棄用,因已在 Spring5 中引入了 WebClient 作為非阻塞式 Reactive HTTP 客戶端。

	(2RestTemplate 定義了 36 個(gè)與 REST 資源交互的方法,其中的大多數(shù)都對(duì)應(yīng)于 HTTP 的方法。
	注意:
		嚴(yán)格來(lái)說只有 11 個(gè)獨(dú)立的方法,其中有 10 個(gè)有三種重載形式,
				而第 11 個(gè)則重載了 6 次,這樣一共形成了 36 個(gè)方法。
		實(shí)際上,由于 Post 操作的非冪等性,它幾乎可以代替其他的 CRUD 操作。
	// 方法列表如下:
	delete():這個(gè)方法是在特定的 URL 上對(duì)資源執(zhí)行 HTTP DELETE 操作
	exchange():在 URL 上執(zhí)行特定的 HTTP 方法,返回包含對(duì)象的 ResponseEntity,這個(gè)對(duì)象是從響應(yīng)體中映射得到的
	execute():在 URL 上執(zhí)行特定的 HTTP 方法,返回一個(gè)從響應(yīng)體映射得到的對(duì)象
	getForEntity():發(fā)送一個(gè) HTTP GET 請(qǐng)求,返回的 ResponseEntity 包含了響應(yīng)體所映射成的對(duì)象
	getForObject():發(fā)送一個(gè) HTTP GET 請(qǐng)求,返回的請(qǐng)求體將映射為一個(gè)對(duì)象
	postForEntity():POST 數(shù)據(jù)到一個(gè) URL,返回包含一個(gè)對(duì)象的 ResponseEntity,這個(gè)對(duì)象是從響應(yīng)體中映射得到的
	postForObject():POST 數(shù)據(jù)到一個(gè) URL,返回根據(jù)響應(yīng)體匹配形成的對(duì)象
	headForHeaders():發(fā)送 HTTP HEAD 請(qǐng)求,返回包含特定資源 URL 的 HTTP 頭
	optionsForAllow():發(fā)送 HTTP OPTIONS 請(qǐng)求,返回對(duì)特定 URL 的 Allow 頭信息
	postForLocation():POST 數(shù)據(jù)到一個(gè) URL,返回新創(chuàng)建資源的 URL
	put():PUT 資源到特定的 URL

2. 安裝配置

2-1 引入Maven依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2-2 創(chuàng)建 RestTemplate 配置類,設(shè)置連接池大小、超時(shí)時(shí)間、重試機(jī)制等等。

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }
 
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(15000); // 連接超時(shí)
        factory.setReadTimeout(5000); // 數(shù)據(jù)讀取超時(shí)時(shí)間
        return factory;
    }
}

3. 使用示例

@RestController
public class HelloController {
    @Autowired
    private RestTemplate restTemplate;
 
    @GetMapping("/test")
    public String test() {
    	// 發(fā)起Get請(qǐng)求,獲取接口返回的字符串
        String url = "http://jsonplaceholder.typicode.com/posts/1";
        return restTemplate.getForObject(url, String.class);
    }
}

4 GET 請(qǐng)求1:getForObject() 方法的使用

4-1 使用示例

// 		2-1 測(cè)試用的實(shí)體Bean
@Getter
@Setter
@ToString
public class PostBean {
    private int userId;
    private int id;
    private String title;
    private String body;
}
// getForObject() 用于發(fā)送一個(gè) HTTP GET 請(qǐng)求。它和 getForEntity() 用法幾乎相同。
//		區(qū)別在于 getForObject() 返回值返回的是響應(yīng)體,省略了很多 response 的信息。

// 示例1. 獲取 String 結(jié)果數(shù)據(jù)
@RestController
public class HelloController {
    @Autowired
    private RestTemplate restTemplate;
 
    @GetMapping("/test")
    public void test() {
        String url = "http://jsonplaceholder.typicode.com/posts/1";
        String str = restTemplate.getForObject(url, String.class);
        System.out.println(str);
        return;
    }
}

// 示例2. 將結(jié)果轉(zhuǎn)換為對(duì)象
//		由于 getForObject() 包含了將 HTTP 結(jié)果轉(zhuǎn)成 POJO 的功能,所以我們可以將其轉(zhuǎn)換成自定義的實(shí)體類對(duì)象
@RestController
public class HelloController {
    @Autowired
    private RestTemplate restTemplate;
 
    @GetMapping("/test")
    public void test() {
        String url = "http://jsonplaceholder.typicode.com/posts/1";
        PostBean postBean = restTemplate.getForObject(url, PostBean.class);
        System.out.println(postBean.toString());
        return;
    }
}

// 示例3. 將結(jié)果轉(zhuǎn)成數(shù)組,如下實(shí)例返回對(duì)象數(shù)組
//		假設(shè)接口返回的是一個(gè) json 數(shù)組--實(shí)體對(duì)應(yīng)上述的PostBean :
@RestController
public class HelloController {
    @Autowired
    private RestTemplate restTemplate;
 
    @GetMapping("/test")
    public void test() {
        String url = "http://jsonplaceholder.typicode.com/posts";
        PostBean[] arr = restTemplate.getForObject(url, PostBean[].class);
        System.out.println("結(jié)果數(shù):" + arr.length);
        return;
    }
}

4-2 參數(shù)傳遞的幾種方式

// 1. 使用占位符的形式傳遞參數(shù):
String url = "http://jsonplaceholder.typicode.com/{1}/{2}";
PostBean postBean = restTemplate.getForObject(url, PostBean.class, "posts", 1);

// 2. 另一種使用占位符的形式,填充變量:
String url = "http://jsonplaceholder.typicode.com/{type}/{id}";
String type = "posts";
int id = 1;
PostBean postBean = restTemplate.getForObject(url, PostBean.class, type, id);

// 3. 使用 map裝載參數(shù):
String url = "http://jsonplaceholder.typicode.com/{type}/{id}";
Map<String,Object> map = new HashMap<>();
map.put("type", "posts");
map.put("id", 1);
PostBean postBean = restTemplate.getForObject(url, PostBean.class, map);

5 GET 請(qǐng)求2:getForEntity() 方法的使用

5-1 使用示例

getForEntity() 同樣用于發(fā)送一個(gè) HTTP GET 請(qǐng)求。它和 getForObject() 用法幾乎相同。
		區(qū)別在于 getForEntity() 返回的是 ResponseEntityResponseEntitySpring 對(duì) HTTP 請(qǐng)求響應(yīng)的封裝,包括了幾個(gè)重要的元素,
		如響應(yīng)碼、contentType、contentLength、響應(yīng)消息體等。
		其中響應(yīng)消息體可以通過 ResponseEntity 對(duì)象的 getBody() 來(lái)獲取。

// 示例1 -- 返回字符串
@RestController
public class HelloController {
    @Autowired
    private RestTemplate restTemplate;
 
    @GetMapping("/test")
    public void test() {
        String url = "http://jsonplaceholder.typicode.com/posts/5";
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        String body = responseEntity.getBody(); // 獲取響應(yīng)體
        HttpStatus statusCode = responseEntity.getStatusCode(); // 獲取響應(yīng)碼
        int statusCodeValue = responseEntity.getStatusCodeValue(); // 獲取響應(yīng)碼值
        HttpHeaders headers = responseEntity.getHeaders(); // 獲取響應(yīng)頭
 
        System.out.println("body:" + body);
        System.out.println("statusCode:" + statusCode);
        System.out.println("statusCodeValue:" + statusCodeValue);
        System.out.println("headers:" + headers);
        return;
    }
}

// 示例2 -- 將消息體轉(zhuǎn)換為對(duì)象
@RestController
public class HelloController {
    @Autowired
    private RestTemplate restTemplate;
 
    @GetMapping("/test")
    public void test() {
        String url = "http://jsonplaceholder.typicode.com/posts/5";
        ResponseEntity<PostBean> responseEntity = restTemplate.getForEntity(url, PostBean.class);
        PostBean postBean = responseEntity.getBody(); // 獲取響應(yīng)體,其他的參數(shù)獲取,參考示例1
        System.out.println(postBean);
        return;
    }
}

// 示例3 -- 將結(jié)果轉(zhuǎn)成數(shù)組,本例返回對(duì)象數(shù)組
@RestController
public class HelloController { 
    @Autowired
    private RestTemplate restTemplate;
 
    @GetMapping("/test")
    public void test() {
        String url = "http://jsonplaceholder.typicode.com/posts";
        ResponseEntity<PostBean[]> responseEntity = restTemplate.getForEntity(url, PostBean[].class);
        PostBean[] arr = responseEntity.getBody(); // 獲取響應(yīng)體
        System.out.println("結(jié)果數(shù):" + arr.length);
        return;
    }
}		

5-2 參數(shù)傳遞的幾種方式

// 1. 使用占位符的形式傳遞參數(shù):
String url = "http://jsonplaceholder.typicode.com/{1}/{2}";
ResponseEntity<PostBean> responseEntity = restTemplate.getForEntity(url, PostBean.class, "posts", 1);

// 2. 另一種使用占位符的形式,填充變量:
String url = "http://jsonplaceholder.typicode.com/{type}/{id}";
String type = "posts";
int id = 1;
ResponseEntity<PostBean> responseEntity = restTemplate.getForEntity(url, PostBean.class, type, id);

// 3. 使用 map裝載參數(shù):
String url = "http://jsonplaceholder.typicode.com/{type}/{id}";
Map<String,Object> map = new HashMap<>();
map.put("type", "posts");
map.put("id", 1);
ResponseEntity<PostBean> responseEntity = restTemplate.getForEntity(url, PostBean.class, map);

6 POST 請(qǐng)求1:postForObject() 方法的使用

6-1 使用示例

postForObject() 用于發(fā)送一個(gè) HTTP POST 請(qǐng)求。它和 postForEntity() 用法幾乎相同。
		區(qū)別在于 postForObject() 返回值返回的是響應(yīng)體,省略了很多 response 的信息。

// 示例1 -- 發(fā)送一個(gè) JSON 格式數(shù)據(jù),
//		直接將對(duì)象當(dāng)作參數(shù)扔進(jìn)方法postForObject中即可
//			Bean 對(duì)象實(shí)際上會(huì)轉(zhuǎn)成 JSON 數(shù)據(jù)提交:
@RestController
public class HelloController {
    @Autowired
    private RestTemplate restTemplate;
 
    @GetMapping("/test")
    public void test() {
        // 請(qǐng)求地址
        String url = "http://jsonplaceholder.typicode.com/posts";
 
        // 要發(fā)送的數(shù)據(jù)對(duì)象
        PostBean postBean = new PostBean();
        postBean.setUserId(222);
        postBean.setTitle("abc");
        postBean.setBody("航歌");
 
        // 發(fā)送post請(qǐng)求,并輸出結(jié)果
        String result = restTemplate.postForObject(url, postBean, String.class);
        System.out.println(result);
        return;
    }
}

// 示例2 -- 使用 Form 表單的形式提交數(shù)據(jù)
//		使用 POST 方式發(fā)送 multipart/form-data 格式的數(shù)據(jù):
//			最終會(huì)通過 form 表單方式提交數(shù)據(jù)
@RestController
public class HelloController {
    @Autowired
    private RestTemplate restTemplate;
 
    @GetMapping("/test")
    public void test() {
        // 請(qǐng)求地址
        String url = "http://jsonplaceholder.typicode.com/posts";
 
        // 請(qǐng)求頭設(shè)置
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
 
        //提交參數(shù)設(shè)置
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("title", "abc");
        map.add("body", "航歌");
 
        // 組裝請(qǐng)求體
        HttpEntity<MultiValueMap<String, String>> request =
                new HttpEntity<MultiValueMap<String, String>>(map, headers);
 
        // 發(fā)送post請(qǐng)求,并輸出結(jié)果
        String result = restTemplate.postForObject(url, request, String.class);
        System.out.println(result);
        return;
    }
}

// 上述示例是將響應(yīng)結(jié)果以 String 形式接收,
//		還可以自動(dòng)將響應(yīng)結(jié)果轉(zhuǎn)成自定的對(duì)象或則數(shù)組。具體同Get請(qǐng)求類型轉(zhuǎn)換一致:		

6-2 設(shè)置 url 參數(shù),同Get請(qǐng)求

7 POST 請(qǐng)求2:postForEntity()方法的使用

7-1 使用示例,和postForObject()基本相似,返回的是ResponseEntity罷了

postForEntity() 用于發(fā)送一個(gè) HTTP POST 請(qǐng)求。它和上面的 postForObject() 用法幾乎相同。
	區(qū)別在于 getForEntity() 返回的是 ResponseEntityResponseEntitySpring 對(duì) HTTP 請(qǐng)求響應(yīng)的封裝,包括了幾個(gè)重要的元素,
	如響應(yīng)碼、contentType、contentLength、響應(yīng)消息體等。 
	其中響應(yīng)消息體可以通過 ResponseEntity 對(duì)象的 getBody() 來(lái)獲取。

// 示例1 -- 發(fā)送一個(gè) JSON 格式數(shù)據(jù)
@RestController
public class HelloController {
 
    @Autowired
    private RestTemplate restTemplate;
 
    @GetMapping("/test")
    public void test() {
        // 請(qǐng)求地址
        String url = "http://jsonplaceholder.typicode.com/posts";
 
        // 要發(fā)送的數(shù)據(jù)對(duì)象
        PostBean postBean = new PostBean();
        postBean.setUserId(222);
        postBean.setTitle("abc");
        postBean.setBody("航歌");
 
        // 發(fā)送post請(qǐng)求,并輸出結(jié)果
        ResponseEntity<String> responseEntity
                = restTemplate.postForEntity(url, postBean, String.class);
        String body = responseEntity.getBody(); // 獲取響應(yīng)體
        HttpStatus statusCode = responseEntity.getStatusCode(); // 獲取響應(yīng)碼
        int statusCodeValue = responseEntity.getStatusCodeValue(); // 獲取響應(yīng)碼值
        HttpHeaders headers = responseEntity.getHeaders(); // 獲取響應(yīng)頭
 
        System.out.println("body:" + body);
        System.out.println("statusCode:" + statusCode);
        System.out.println("statusCodeValue:" + statusCodeValue);
        System.out.println("headers:" + headers);
        return;
    }
}

7-2 設(shè)置 url 參數(shù),同Get請(qǐng)求

8 POST 請(qǐng)求3:postForLocation() 方法的使用,返回的是 Uri

1postForLocation() 也是通過 Post 方式提交新資源,
		postForLocation() 方法的參數(shù)和前面兩種(postForObject、postForEntity)的參數(shù)基本一致。
2)區(qū)別在于 postForLocation() 方法的返回值為 Uri,這個(gè)只需要服務(wù)提供者返回一個(gè) Uri 即可,
		該 Uri 表示新資源的位置。

// 示例: 比如登錄或者注冊(cè)都是 post 請(qǐng)求,
//		而這些操作完成之后大部分都是跳轉(zhuǎn)到別的頁(yè)面去了。
//		這種場(chǎng)景下,就可以使用 postForLocation 了,提交數(shù)據(jù),并獲取返回的 URI。		
@RestController
public class HelloController {
    @Autowired
    private RestTemplate restTemplate;
 
    @GetMapping("/test")
    public void test() {
        // 請(qǐng)求地址
        String url = "http://jsonplaceholder.typicode.com/posts";
 
        // 要發(fā)送的數(shù)據(jù)對(duì)象
        MultiValueMap<String, String> request = new LinkedMultiValueMap<>();
        request.add("username", "hangge");
        request.add("password", "123456");
 
        // 發(fā)送post請(qǐng)求,并輸出結(jié)果
        URI uri = restTemplate.postForLocation(url, request);
        System.out.println(uri);
        return;
    }
}

9 通用請(qǐng)求方法:exchange

9-1 介紹

1)exchange 的用法同前面介紹的 getForEntity、postForEntity 差不多,且返回的都是 ResponseEntityResponseEntitySpring 對(duì) HTTP 請(qǐng)求響應(yīng)的封裝,包括了幾個(gè)重要的元素,
	如響應(yīng)碼、contentType、contentLength、響應(yīng)消息體等。
	其中響應(yīng)消息體可以通過 ResponseEntity 對(duì)象的 getBody() 來(lái)獲取。
2)不同在于 exchange 方法提供統(tǒng)一的方法模板,可以通過指定不同的 HTTP 請(qǐng)求類型,實(shí)現(xiàn) POST、PUT、DELETE、GET 四種請(qǐng)求。

9-2 Get 請(qǐng)求示例

// 使用 Get 請(qǐng)求,并將響應(yīng)體、響應(yīng)頭、響應(yīng)碼打印出來(lái)。其中響應(yīng)體的類型為 String。
@RestController
public class HelloController {
    @Autowired
    private RestTemplate restTemplate;
 
    @GetMapping("/test")
    public void test() {
        String url = "http://jsonplaceholder.typicode.com/posts/5";
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET,
                null, String.class);
        String body = responseEntity.getBody(); // 獲取響應(yīng)體
        HttpStatus statusCode = responseEntity.getStatusCode(); // 獲取響應(yīng)碼
        int statusCodeValue = responseEntity.getStatusCodeValue(); // 獲取響應(yīng)碼值
        HttpHeaders headers = responseEntity.getHeaders(); // 獲取響應(yīng)頭
 
        System.out.println("body:" + body);
        System.out.println("statusCode:" + statusCode);
        System.out.println("statusCodeValue:" + statusCodeValue);
        System.out.println("headers:" + headers);
        return;
    }
}

9-3 Post 請(qǐng)求示例

// 使用 post 方式發(fā)送一個(gè) JSON 格式的數(shù)據(jù),并將響應(yīng)體、響應(yīng)頭、響應(yīng)碼打印出來(lái)。其中響應(yīng)體的類型設(shè)置為 String
@RestController
public class HelloController {
    @Autowired
    private RestTemplate restTemplate;
 
    @GetMapping("/test")
    public void test() {
        // 請(qǐng)求地址
        String url = "http://jsonplaceholder.typicode.com/posts";
 
        // 請(qǐng)求頭設(shè)置
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
 
        //提交參數(shù)設(shè)置
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("userId", "222");
        map.add("title", "abc");
        map.add("body", "航歌");
 
        // 組裝請(qǐng)求體
        HttpEntity<MultiValueMap<String, String>> request =
                new HttpEntity<MultiValueMap<String, String>>(map, headers);
 
        // 發(fā)送post請(qǐng)求,并輸出結(jié)果
        ResponseEntity<String> responseEntity
                = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
        String body = responseEntity.getBody(); // 獲取響應(yīng)體
        HttpStatus statusCode = responseEntity.getStatusCode(); // 獲取響應(yīng)碼
        int statusCodeValue = responseEntity.getStatusCodeValue(); // 獲取響應(yīng)碼值
        HttpHeaders responseHeaders = responseEntity.getHeaders(); // 獲取響應(yīng)頭
 
        System.out.println("body:" + body);
        System.out.println("statusCode:" + statusCode);
        System.out.println("statusCodeValue:" + statusCodeValue);
        System.out.println("headers:" + responseHeaders);
        return;
    }
}

10 文件下載

10-1 簡(jiǎn)單的文件下載

1)最簡(jiǎn)單的下載文件方式就是使用的是 restTemplate 調(diào)用 getForEntity 獲取到字節(jié)數(shù)組,
	再將字節(jié)數(shù)組通過 java8 的 Files 工具類的 write 方法,直接寫到目標(biāo)文件。
	
? 	缺點(diǎn):由于需要將文件的字節(jié)數(shù)組全部放入內(nèi)存中,極其消耗資源。
	當(dāng)遇到大文件時(shí),內(nèi)存加載可能會(huì)造成 OutOfMemoryError。

2)下面是一個(gè)簡(jiǎn)單的示例,下載一個(gè)網(wǎng)絡(luò)上的圖片并保存到本地。
@RestController
public class HelloController {
    @Autowired
    private RestTemplate restTemplate;
 
    @GetMapping("/test")
    public void test() {
        // 記錄下開始下載時(shí)的時(shí)間
        Instant now = Instant.now();
        // 待下載的文件地址
        String url = "http://www.hangge.com/blog/images/logo.png";
        ResponseEntity<byte[]> rsp = restTemplate.getForEntity(url, byte[].class);
        System.out.println("狀態(tài)碼:" + rsp.getStatusCode());
        try {
            // 將下載下來(lái)的文件內(nèi)容保存到本地
            String targetPath = "/Users/hangge/Desktop/logo.png";
            Files.write(Paths.get(targetPath), Objects.requireNonNull(rsp.getBody(),
                    "未獲取到下載文件"));
        } catch (IOException e) {
            System.out.println("文件寫入失?。? + e.getMessage());
        }
        System.out.println("文件下載完成,耗時(shí):" + ChronoUnit.MILLIS.between(now, Instant.now())
                + " 毫秒");
        return;
    }
}

10-2 大文件的下載

// 對(duì)于大文件的下載,建議使用流的方式來(lái)解決。
//	即每次接收到一部分?jǐn)?shù)據(jù)就直接寫入到文件。比如使用 Files 的 copy 方法來(lái)處理流。
@RestController
public class HelloController {
    @Autowired
    private RestTemplate restTemplate;
 
    @GetMapping("/test")
    public void test() {
        // 記錄下開始下載時(shí)的時(shí)間
        Instant now = Instant.now();
        // 待下載的文件地址
        String url = "http://www.hangge.com/blog/images/logo.png";
        // 文件保存的本地路徑
        String targetPath = "/Users/hangge/Desktop/logo.png";
        //定義請(qǐng)求頭的接收類型
        RequestCallback requestCallback = request -> request.getHeaders()
                .setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));
        //對(duì)響應(yīng)進(jìn)行流式處理而不是將其全部加載到內(nèi)存中
        restTemplate.execute(url, HttpMethod.GET, requestCallback, clientHttpResponse -> {
            Files.copy(clientHttpResponse.getBody(), Paths.get(targetPath));
            return null;
        });
        
        System.out.println("文件下載完成,耗時(shí):" + ChronoUnit.MILLIS.between(now, Instant.now())
                + " 毫秒");
        return;
    }
}

11 文件上傳

11-1 示例

1)下面通過樣例演示如何使用 RestTemplate 上傳文件。
	這里使用 Form 表單的方式進(jìn)行提交,上傳時(shí)除了一個(gè)文件外還附帶有兩個(gè)自定義參數(shù)。
2)接收端收到文件后會(huì)打印出相關(guān)參數(shù)、以及文件相關(guān)數(shù)據(jù),并返回成功信息。
3)發(fā)送方收到反饋后將反饋信息打印出來(lái):

// 簡(jiǎn)單的示例,如要進(jìn)一步操作,比如:文件重命名、文件保存、相關(guān)上傳參數(shù)的配置等自己完善哈
// 1. 文件發(fā)送端代碼:
@RestController
public class HelloController {
    @Autowired
    private RestTemplate restTemplate;
 
    @GetMapping("/test")
    public void test() {
        // 上傳接口
        String url = "http://localhost:8080/upload";
        // 待上傳的文件
        String filePath = "/Users/hangge/Desktop/test.txt";
 
        // 封裝請(qǐng)求參數(shù)
        FileSystemResource resource = new FileSystemResource(new File(filePath));
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("myFile", resource);
        param.add("param1", "12345");
        param.add("param2", "hangge");
 
        // 發(fā)送請(qǐng)求并輸出結(jié)果
        System.out.println("--- 上傳文件 ---");
        String s = restTemplate.postForObject(url, param, String.class);
        System.out.println(s);
    }
}


// 2. 接收端代碼:  
@RestController
public class HelloController {
    @PostMapping("/upload")
    public String upload(String param1, String param2, MultipartFile myFile) {
        System.out.println("--- 接收文件 ---");
        System.out.println("param1:" + param1);
        System.out.println("param2:" + param2);
        String originalFilename = myFile.getOriginalFilename();
        System.out.println("文件原始名稱:" + originalFilename);
        try {
            String string = new String(myFile.getBytes(), "UTF-8");
            System.out.println("文件內(nèi)容:" + string);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 處理文件內(nèi)容...
        return "OK";
    }
}


文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-433448.html

到了這里,關(guān)于SpringBoot中RestTemplate的使用備忘的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • SpringBoot 使用 RestTemplate 發(fā)送 binary 數(shù)據(jù)流

    SpringBoot 使用 RestTemplate 發(fā)送 binary 數(shù)據(jù)流

    情況說明: 接口A接受到一個(gè)數(shù)據(jù)流,在postman里的傳輸方式顯示如下: 接口A接受到這個(gè)數(shù)據(jù)流之后,需要轉(zhuǎn)發(fā)到接口B進(jìn)行處理。 這里要注意一點(diǎn)是: postman圖中的這種方式和MultipartFile流的傳輸方式不同,MultipartFile流方式,是在body的form表單中進(jìn)行傳輸,需要指定一個(gè)key,這

    2024年02月12日
    瀏覽(20)
  • SpringBoot | RestTemplate異常處理器ErrorHandler使用詳解

    SpringBoot | RestTemplate異常處理器ErrorHandler使用詳解

    關(guān)注wx:CodingTechWork ??在代碼開發(fā)過程中,發(fā)現(xiàn)很多地方通過 RestTemplate 調(diào)用了第三方接口,而第三方接口需要根據(jù)某些狀態(tài)碼或者異常進(jìn)行重試調(diào)用,此時(shí),要么在每個(gè)調(diào)用的地方進(jìn)行異常捕獲,然后重試;要么在封裝的 RestTemplate 工具類中進(jìn)行統(tǒng)一異常捕獲和封裝。當(dāng)然

    2024年02月12日
    瀏覽(17)
  • SpringBoot之RestTemplate使用Apache的HttpClient連接池

    SpringBoot自帶的RestTemplate是沒有使用連接池的,只是SimpleClientHttpRequestFactory實(shí)現(xiàn)了ClientHttpRequestFactory、AsyncClientHttpRequestFactory 2個(gè)工廠接口,因此每次調(diào)用接口都會(huì)創(chuàng)建連接和銷毀連接,如果是高并發(fā)場(chǎng)景下會(huì)大大降低性能。因此,我們可以使用Apache的HttpClient連接池。

    2024年02月11日
    瀏覽(19)
  • SpringBoot中RestTemplate和WebClient的使用區(qū)別及優(yōu)缺點(diǎn)含完整代碼

    點(diǎn)擊下載《SpringBoot中RestTemplate和WebClient的使用區(qū)別及優(yōu)缺點(diǎn)含完整代碼》 本文將深入探討Spring Boot中RestTemplate和WebClient的用法、區(qū)別和優(yōu)缺點(diǎn)。通過具體的代碼示例,我們將詳細(xì)解釋這兩種HTTP客戶端的使用方法,并分析它們?cè)诓煌瑘?chǎng)景下的適用性。 RestTemplate是Spring框架中用

    2024年02月19日
    瀏覽(26)
  • SpringBoot RestTemplate詳解

    SpringBoot RestTemplate詳解

    參考自:http://events.jianshu.io/p/477e7a3179c6 大家都知道在SpringBoot中一般適用RestTemplate來(lái)進(jìn)行遠(yuǎn)程調(diào)用,那么SpringBoot中如何默認(rèn)配置RestTemplate,以及如何自定義配置自己的RestTemplate,RestTemplate異步請(qǐng)求如何實(shí)現(xiàn)等 RestTemplate是Spring提供的進(jìn)行遠(yuǎn)程調(diào)用客戶端 RestTemplate提供了很多遠(yuǎn)

    2024年02月06日
    瀏覽(12)
  • springboot(39) : RestTemplate完全體

    ? ? ? ? HTTP請(qǐng)求調(diào)用集成,支持GET,POST,JSON,Header,文件上傳調(diào)用,日志打印,請(qǐng)求耗時(shí)計(jì)算,設(shè)置中文編碼 需要安裝lombok插件??

    2024年02月14日
    瀏覽(14)
  • SpringBoot整合RestTemplate用法講解(完整詳細(xì))

    前言:本篇主要介紹了RestTemplate中的GET,POST,PUT,DELETE、文件上傳和文件下載6大常用的功能,每一個(gè)方法和每一行代碼都進(jìn)行了詳細(xì)的講解,代碼都是親自測(cè)試過的,整篇博客寫完以后自己也是受益匪淺,于是在這做個(gè)技術(shù)分享! 目錄 一、RestTemplate簡(jiǎn)介 二、基礎(chǔ)配置 2.1、

    2024年02月12日
    瀏覽(27)
  • Springboot -- 用更優(yōu)雅的方式發(fā)HTTP請(qǐng)求(RestTemplate詳解)

    Springboot -- 用更優(yōu)雅的方式發(fā)HTTP請(qǐng)求(RestTemplate詳解)

    RestTemplate 是 Spring 提供的用于訪問Rest服務(wù)的客戶端, RestTemplate 提供了多種便捷訪問遠(yuǎn)程Http服務(wù)的方法,能夠大大提高客戶端的編寫效率。 我之前的HTTP開發(fā)是用apache的HttpClient開發(fā),代碼復(fù)雜,還得操心資源回收等。代碼很復(fù)雜,冗余代碼多,稍微截個(gè)圖,這是我封裝好的一

    2024年02月02日
    瀏覽(21)
  • 【Spring Cloud系列】- RestTemplate使用詳解

    RestTemplate是Spring框架提供用于調(diào)用Rest接口的一個(gè)應(yīng)用,它簡(jiǎn)化了與http服務(wù)通信方式。RestTemplate統(tǒng)一Restfull調(diào)用的標(biāo)準(zhǔn),封裝HTTP鏈接,只要需提供URL及返回值類型即可完成調(diào)用。相比傳統(tǒng)的HttpClient與Okhttp,RestTemplate是一種優(yōu)雅,簡(jiǎn)潔調(diào)用RESTfull服務(wù)的方式。 RestTemplate默認(rèn)依賴

    2024年02月08日
    瀏覽(25)
  • java使用RestTemplate發(fā)送Get請(qǐng)求

    使用RestTemplate的 getForObject() 或 getForEntity() , getForObject() 只有響應(yīng)體, getForEntity() 包含HTTP響應(yīng)的全部信息,以常用的 getForObject() 為例: 傳入兩個(gè)參數(shù):1. url 2. 響應(yīng)數(shù)據(jù)類型 這里演示了以字符串形式接收get響應(yīng)的例子: 需要注意的是,當(dāng)get請(qǐng)求的接口響應(yīng)的 Content-Type 是

    2024年02月15日
    瀏覽(24)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包