Java?Http請(qǐng)求方式之RestTemplate常用方法詳解
引言
在開發(fā)中有時(shí)候經(jīng)常需要一些Http請(qǐng)求,請(qǐng)求數(shù)據(jù),下載內(nèi)容,也有一些簡(jiǎn)單的分布式應(yīng)用直接使用Http請(qǐng)求作為跨應(yīng)用的交互協(xié)議。
在Java中有不同的Http請(qǐng)求方式,主要就是HttpURLConnection或者ApacheHttpClient,但是這兩個(gè)用起來都感覺有那么一點(diǎn)點(diǎn)的復(fù)雜;
好在Spring內(nèi)置了RestTemplate作為Http請(qǐng)求的工具類,簡(jiǎn)化了很多操作,雖然Spring5推出了WebClient,但是整體感覺還是RestTemplate用起來更簡(jiǎn)單方便一些。
這里記錄分享下RestTemplate的常見使用方式,RestTemplate作為Java中最簡(jiǎn)單好用的Http請(qǐng)求工具類一定要了解一下
常見用法
簡(jiǎn)單Get\Post請(qǐng)求
@Test
public void testGetPost(){
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());
String res = restTemplate.postForObject("http://test.aihe.space/", null, String.class);
System.out.println(res);
String res2 = restTemplate.getForObject("http://test.aihe.space/", String.class);
System.out.println(res2);
}
Post提交常規(guī)表單
@Test
public void testPostFrom(){
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add("id", "1");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
String fooResourceUrl = "http://test.aihe.space/";
ResponseEntity<String> response = restTemplate.postForEntity(fooResourceUrl, request, String.class);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
}
Post上傳文件
注意:上傳文件時(shí)的value為FileSystemResource
@Test
public void testPostFile(){
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> map= new LinkedMultiValueMap<>();
map.add("id", "1");
map.add("file",new FileSystemResource("/Users/aihe/code/init/src/test/java/me/aihe/RestTemplateTest.java"));
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);
String fooResourceUrl = "http://test.aihe.space/";
ResponseEntity<String> response = restTemplate.postForEntity(fooResourceUrl, request, String.class);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
}
配置項(xiàng)
請(qǐng)求添加Cookie\Header
@Test
public void testCookieHeader(){
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> map= new LinkedMultiValueMap<>();
// 常見的Header都可以直接設(shè)置
// headers.set
headers.set("custom1","customValue1");
// 設(shè)置Cookie
headers.set(HttpHeaders.COOKIE,"xxxx");
map.add("id", "1");
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);
String fooResourceUrl = "http://test.aihe.space/";
ResponseEntity<String> response = restTemplate.postForEntity(fooResourceUrl, request, String.class);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
}
配置請(qǐng)求工廠 超時(shí)、代理
使用Rest請(qǐng)求的時(shí)候注意設(shè)置超時(shí)時(shí)間
@Test
public void testHttpFactory(){
RestTemplate restTemplate = new RestTemplate();
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setReadTimeout(5000);
requestFactory.setConnectTimeout(3000);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 7890));
requestFactory.setProxy(proxy);
restTemplate.setRequestFactory(requestFactory);
restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());
String res = restTemplate.postForObject("http://test.aihe.space/", null, String.class);
System.out.println(res);
}
配置攔截器、轉(zhuǎn)換器,錯(cuò)誤處理
@Test
public void testConverterInterceptor(){
RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(Collections.singletonList(new BasicAuthenticationInterceptor("admin","admin")));
restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());
restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
String res = restTemplate.postForObject("http://test.aihe.space/", null, String.class);
System.out.println(res);
}
錯(cuò)誤重試(額外)
可以考慮使用Spring Retry,但是相當(dāng)于引入了新的東西,如果沒有特殊必要,可以自己簡(jiǎn)單用for循環(huán)做下;
SSL請(qǐng)求
參考:stackoverflow.com/questions/1…
@Test
public void testSSL() throws FileNotFoundException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
String keyStorePassword = "123456";
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(new FileInputStream(new File("keyStoreFile")),
keyStorePassword.toCharArray());
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
new SSLContextBuilder()
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.loadKeyMaterial(keyStore, keyStorePassword.toCharArray())
.build(),
NoopHostnameVerifier.INSTANCE);
HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(
socketFactory).build();
ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
String res = restTemplate.postForObject("http://test.aihe.space/", null, String.class);
System.out.println(res);
}
基于RestTemplate一些工具
釘釘機(jī)器人通知
可以支持發(fā)送普通文本、ActionCard,Markdown的消息
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
/**
* 使用場(chǎng)景:
* 功能描述:https://developers.dingtalk.com/document/app/custom-robot-access/title-72m-8ag-pqw
*/
@Slf4j
public class RobotUtils {
private static RestTemplate restTemplate = new RestTemplate();
private static String URL = "";
public static void main(String[] args) {
sendMarkDownMsg(
URL,
"測(cè)試",
"測(cè)試",
new ArrayList<>()
);
}
/**
* {
* "msgtype": "text",
* "text": {
* "content": "我就是我, @150XXXXXXXX 是不一樣的煙火"
* },
* "at": {
* "atMobiles": [
* "150XXXXXXXX"
* ],
* "isAtAll": false
* }
* }
*/
public static void sendTextMsg(String url, String content, List<String> atPerson) {
RobotMsg robotMsg = new RobotMsg();
robotMsg.setMsgtype("text");
RobotAt robotAt = new RobotAt();
robotAt.setAtAll(false);
if (atPerson != null && atPerson.size() > 0) {
robotAt.setAtMobiles(atPerson);
}
robotMsg.setAt(robotAt);
RobotText robotText = new RobotText();
robotText.setContent(content);
robotMsg.setText(robotText);
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, robotMsg, String.class);
log.info("sendTextMsg {}",responseEntity.getBody());
}
/**
* @param url 機(jī)器人地址
* @param title actionCard標(biāo)題
* @param text 縮略內(nèi)容
* @param vertical 按鈕方向
* @param btns 按鈕內(nèi)容
*/
public static void sendActionCardMsg(String url, String title, String text, Boolean vertical, List<RobotBtn> btns) {
RobotMsg robotMsg = new RobotMsg();
robotMsg.setMsgtype("actionCard");
RobotAt robotAt = new RobotAt();
robotAt.setAtAll(false);
RobotActionCard robotActionCard
= new RobotActionCard();
robotActionCard.setTitle(title);
robotActionCard.setText(text);
robotActionCard.setBtnOrientation((vertical == null || vertical) ? "0" : "1");
robotActionCard.setBtns(btns);
robotMsg.setActionCard(robotActionCard);
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, robotMsg, String.class);
System.out.println(responseEntity.getBody());
}
public static void sendMarkDownMsg(String url,String title,String text,List<String> atPerson){
RobotMarkDownMsg markDownMsg = new RobotMarkDownMsg();
markDownMsg.setMsgtype("markdown");
RobotAt robotAt = new RobotAt();
robotAt.setAtAll(false);
if (atPerson != null && atPerson.size() > 0) {
robotAt.setAtMobiles(atPerson);
}
markDownMsg.setAt(robotAt);
RobotMarkdownText markdownText = new RobotMarkdownText();
markdownText.setTitle(title);
markdownText.setText(text);
markDownMsg.setMarkdown(markdownText);
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, markDownMsg, String.class);
System.out.println(responseEntity.getBody());
}
public enum SupportRobotEnum {
/**
* 測(cè)試機(jī)器人群
*/
CESHI("測(cè)試機(jī)器人群",
"");
@Getter
private String desc;
@Getter
private String url;
SupportRobotEnum(String desc, String url) {
this.desc = desc;
this.url = url;
}
}
@Data
public static class RobotAt {
public List<String> atMobiles;
public boolean isAtAll;
}
@Data
public static class RobotMarkDownMsg{
public String msgtype;
public RobotAt at;
public RobotMarkdownText markdown;
}
@Data
public static class RobotMarkdownText {
String title;
String text;
}
@Data
public static class RobotMsg {
public String msgtype;
public RobotAt at;
/**
* 普通文字消息類型消息
*/
public RobotText text;
/**
* actionCard類型消息時(shí)支持
*/
public RobotActionCard actionCard;
}
@Data
public static class RobotText {
public String content;
}
@Data
public static class RobotActionCard {
public String title;
public String text;
public String hideAvatar;
public String btnOrientation;
public List<RobotBtn> btns;
}
@Data
public static class RobotBtn {
public String title;
public String actionURL;
public static RobotBtn buildBtn(String title, String actionUrl) {
RobotBtn robotBtn = new RobotBtn();
robotBtn.setActionURL(actionUrl);
robotBtn.setTitle(title);
return robotBtn;
}
}
}
總結(jié)
1、 Http請(qǐng)求在開發(fā)過程中也是一個(gè)常見的高頻操作;
2、Spring封裝了Http的工具類RestTemplate非常好用,基本上滿足了所有Http相關(guān)的需求。
3、這里介紹整理了下RestTemplate的常見使用方式,遇到有對(duì)應(yīng)的內(nèi)容,直接翻閱使用即可。
以上就是Java Http請(qǐng)求方式之RestTemplate常用方法詳解的詳細(xì)內(nèi)容,更多關(guān)于Java Http請(qǐng)求方式RestTemplate的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java中對(duì)list元素進(jìn)行排序的方法詳解
這篇文章主要介紹了Java中對(duì)list元素進(jìn)行排序的方法詳解,是Java入門學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-09-09
SpringBoot使用RabbitMQ延時(shí)隊(duì)列(小白必備)
這篇文章主要介紹了SpringBoot使用RabbitMQ延時(shí)隊(duì)列(小白必備),詳細(xì)的介紹延遲隊(duì)列的使用場(chǎng)景及其如何使用,需要的小伙伴可以一起來了解一下2019-12-12
Java開發(fā)之內(nèi)部類對(duì)象的創(chuàng)建及hook機(jī)制分析
這篇文章主要介紹了Java開發(fā)之內(nèi)部類對(duì)象的創(chuàng)建及hook機(jī)制,結(jié)合實(shí)例形式分析了java基于hook機(jī)制內(nèi)部類對(duì)象的創(chuàng)建與使用,需要的朋友可以參考下2018-01-01
解決springboot項(xiàng)目打成jar包后運(yùn)行時(shí)碰到的小坑
這篇文章主要介紹了解決springboot項(xiàng)目打成jar包后運(yùn)行時(shí)碰到的小坑,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02
Spring Boot + Mybatis多數(shù)據(jù)源和動(dòng)態(tài)數(shù)據(jù)源配置方法
最近做項(xiàng)目遇到這樣的應(yīng)用場(chǎng)景,項(xiàng)目需要同時(shí)連接兩個(gè)不同的數(shù)據(jù)庫A, B,并且它們都為主從架構(gòu),一臺(tái)寫庫,多臺(tái)讀庫。下面小編給大家?guī)砹薙pring Boot + Mybatis多數(shù)據(jù)源和動(dòng)態(tài)數(shù)據(jù)源配置方法,需要的朋友參考下吧2018-01-01
關(guān)于struts返回對(duì)象json格式數(shù)據(jù)的方法
以下為大家介紹,關(guān)于struts返回對(duì)象json格式數(shù)據(jù)的方法,希望對(duì)有需要的朋友有所幫助。2013-04-04

