RestTemplate之post,get請求


1.RestTemplate之post請求

A.帶header並傳遞給第三方數據格式如下

{
    "version": "1.0.0",
    "token": "token",
    "sign": "sign"
}

如下組織數據與傳遞

// header數據
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Basic xxx");
headers.set("Content-Type", "application/json");
headers.set("Accept", "application/json");

// 組織要傳遞的數據
Map<String,Object> requestBody = new HashedMap();
requestBody.put("version", "1.0.0");
requestBody.put("token", "token");
requestBody.put("sign", "sign");

String  requestUrl = "請求的URL";
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers); 
RestTemplate restTemplate
= new RestTemplate();
ResponseEntity
<String> response = restTemplate.postForEntity(requestUrl, requestEntity, String.class);

接收方收到數據格式如下

 

{
    "token": "token",
    "sign": "sign",
    "version": "1.0.0"
}

 

 

 

B.帶header並傳遞給第三方數據格式如下

{
    "action": "action",
    "body": {
        "version": "version",
        "sign": "sign",
        "content": {
            "id": "1",
            "name": "name"
        }
    }
}

如下組織與傳遞

// header數據
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Basic xxx");
headers.set("Content-Type", "application/json");
headers.set("Accept", "application/json");

// 組織數據
Map<String, Object> paramMap = new HashedMap();
Map<String,Object> subMap = new HashedMap();
Map<String,String> bodyText = new HashedMap();

bodyText.put("id","1");
bodyText.put("name","name");

subMap.put("version","version");
subMap.put("sign","sign");
subMap.put("content",bodyText);

paramMap.put("action", "action");
paramMap.put("body", subMap);

String requestUrl = "請求的URL";

HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(paramMap, headers);
RestTemplate restTemplate = new RestTemplate(); 
ResponseEntity<String> response = restTemplate.exchange(requestUrl, HttpMethod.POST, httpEntity, String.class, paramMap);

 接收方收到數據格式如下

{
    "action": "action",
    "body": {
        "content": {
            "name": "name",
            "id": "1"
        },
        "sign": "sign",
        "version": "version"
    }
}

 2.RestTemplate之get請求

A.傳遞header並通過URL傳遞參數 a=AA&b=BB

 

// header數據
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Basic xxx");
headers.set("Content-Type", "application/json");
headers.set("Accept", "application/json");

String requestUrl = "請求的URL?a=AA&b=BB";
Map<String,Object> paramMap = new HashedMap();
HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(paramMap, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange(requestUrl, HttpMethod.GET, httpEntity, String.class, paramMap);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM