Java筆記-使用RestTemplate發送http數據包(get與post)

最近看項目,方面大佬們都喜歡用RestTemplate去發送http報文,在此記錄下,方便下次使用

這裏只舉get和post例子。

 

get例子。

程序運行截圖如下:

後臺:

源碼如下:

這裏要先配置下config

代碼如下:

package cn.it1995.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class AppConfig {

    @Bean
    public RestTemplate restTemplate(){

        return new RestTemplate();
    }
}

get方式源碼如下:

MyController.java

package cn.it1995.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


@RestController
public class MyController {

    @Autowired
    private RestTemplate restTemplate;


    @GetMapping("/getMsg")
    public Object sendMsg(@RequestParam("msg") String msg){


        ResponseEntity<String> forEntity = restTemplate.getForEntity(msg, String.class);

        System.out.println("------------head start------------");
        System.out.println(forEntity.getHeaders());
        System.out.println("------------head end------------");

        System.out.println("------------body start------------");
        System.out.println(forEntity.getBody());
        System.out.println("------------body end------------");
        System.out.println("\n\n");

        return null;
    }
}

下面是另外一個開源程序的例子,在此我直接貼下代碼,post請求

    @PostMapping("/loginByQQ")
    public Object loginByQQ(String token, HttpServletResponse response, HttpServletRequest request){

        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap();
        paramMap.add("token", token);
        ResponseEntity<Object> objectResponseEntity = restTemplate.postForEntity("http://127.0.0.7:8081/getLoginInfo", paramMap, Object.class);
        Object body = objectResponseEntity.getBody();
        String uuid = CookieUtil.setLoginCookie(request, response);

        //json標準化
        String newJson = body.toString().replace("=", ":");
        System.out.println(newJson);

        Map map = JSON.parseObject(newJson, Map.class);
        Map data = JSON.parseObject(map.get("data").toString(), Map.class);
        user.put(uuid, data);
        return Result.success();
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章