# RestTemplate

## **GET请求**

### **getForEntity**

getForEntity方法的返回值是一个ResponseEntity\<T>，ResponseEntity\<T>是Spring对HTTP请求响应的封装，包括了几个重要的元素，如响应码、contentType、contentLength、响应消息体等

```java
@RequestMapping("/getForEntity")
public ResponseEntity<String> getForEntity() {
      ResponseEntity<String> response = restTemplate.getForEntity("http://app-itmayiedu-member/getMember",
                 String.class);
      System.out.println("statusCode:" + response.getStatusCode());
      System.out.println("Body:" + response.getBody());
      return response;
}
```

getForEntity的第一个参数为我要调用的服务的地址，这里我调用了服务提供者提供的/hello接口，注意这里是通过服务名调用而不是服务地址，如果写成服务地址就没法实现客户端负载均衡了。

getForEntity第二个参数String.class表示我希望返回的body类型是String

拿到返回结果之后，将返回结果遍历打印出来

#### **Get请求传递参数**

```java
@RequestMapping("/getForOrderEntity2")
public ResponseEntity<String> getForEntity2(String name) {
      Map<String, String> map = new HashMap<String, String>();
      map.put("name", name);
      ResponseEntity<String> response = restTemplate.getForEntity("http://app-itmayiedu-member/getUser?name={name}",
                 String.class, map);
      System.out.println("statusCode:" + response.getStatusCode());
      System.out.println("Body:" + response.getBody());
      return response;
}
```

可以用一个数字做占位符，最后是一个可变长度的参数，来一一替换前面的占位符

也可以前面使用name={name}这种形式，最后一个参数是一个map，map的key即为前边占位符的名字，map的value为参数值

### **getForObject**

getForObject函数实际上是对getForEntity函数的进一步封装，如果你只关注返回的消息体的内容，对其他信息都不关注，此时可以使用getForObject，举一个简单的例子，如下：

```java
@RequestMapping("/getOrder")
public String getOrder() {
      // 有两种方式，一种是采用服务别名方式调用，另一种是直接调用 使用别名去注册中心上获取对应的服务调用地址
      String url = "http://app-itmayiedu-member/getMember";
      String result = restTemplate.getForObject(url, String.class);
      System.out.println("订单服务调用会员服务result:" + result);
      return result;
}
```

## **POST请求**

### **PostForEntity**

### **postForObject**

如果你只关注，返回的消息体，可以直接使用postForObject。用法和getForObject一致

## **PUT请求**

## **DELETE请求**


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xiaoxiami.gitbook.io/spring-cloud/fu-wu-xiao-fei-zhe/resttemplate.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
