HttpClient的替代者 - RestTemplate

來源:互聯網
上載者:User

標籤:ica   app   cal   end   autowire   auto   request   接收   風格   

需要的包 ,除了Spring的基礎包外還用到json的包,這裡的資料轉送使用json格式  
用戶端和服務端都用到一下的包
 <!-- Spring -->        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-context</artifactId>            <version>${org.springframework-version}</version>            <exclusions>                <!-- Exclude Commons Logging in favor of SLF4j -->                <exclusion>                    <groupId>commons-logging</groupId>                    <artifactId>commons-logging</artifactId>                 </exclusion>            </exclusions>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-webmvc</artifactId>            <version>${org.springframework-version}</version>        </dependency><!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->          <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId>jackson-core</artifactId>            <version>2.8.1</version>        </dependency>          <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->         <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId>jackson-databind</artifactId>            <version>2.8.1</version>        </dependency>                 <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->         <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId>jackson-annotations</artifactId>            <version>2.8.1</version>        </dependency>  

 

一、伺服器端代碼如下,主要是提供兩個介面@Controller@RequestMapping("/rest")public class RestController {  //http://localhost:8080/Springmvc/rest/getPerson    @RequestMapping(value="/getPerson",method=RequestMethod.GET)    @ResponseBody    public Person getPerson(Integer id){        System.out.println("getPerson..."+id);        Person p = new Person("tom", 12);        return p;    }      //http://localhost:8080/Springmvc/rest/postPerson    @ResponseBody    @RequestMapping(value="/postPerson",method=RequestMethod.POST)    public Person postPerson(@RequestBody Person p){        //@RequestBody用於接收傳來的對象,不加的話會接收不到資料        System.out.println("call postPerson :"+p);        return p;    }}

 

二、用戶端代碼:

1. HttpClient風格的

package com.mvc.rest;import java.io.IOException;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.HttpClients;import com.fasterxml.jackson.core.JsonParseException;import com.fasterxml.jackson.databind.JsonMappingException;import com.fasterxml.jackson.databind.ObjectMapper;import com.mvc.entity.Person;public class MyClient {        /**     * 需要apache的http包和json包     * */    public static void main(String[] args) throws JsonParseException, JsonMappingException, UnsupportedOperationException, IOException {                //HttpClient是Apache的        HttpClient client = HttpClients.createDefault();        HttpGet request = new HttpGet("http://localhost:8080/Springmvc/rest/getPerson?id=1");        request.setHeader("Accept", "application/json");        HttpResponse response = client.execute(request);        HttpEntity entity = response.getEntity();                //利用json的ObjectMapper把請求到的資料轉化為對象        ObjectMapper mapper = new ObjectMapper();        Person p =mapper.readValue(entity.getContent(), Person.class);        System.out.println(p);    }}

 

2.RestTemplate 風格的

import org.springframework.web.client.RestTemplate;

  
Spring提供的Rest風格的RestTemplate比Apache的HttpClient操作更方便

  @Bean(name="restTemplate") public RestTemplate restTemp(){ return new RestTemplate(); }
  @Autowired    private RestTemplate re;        @RequestMapping("/testRestTemplate")    public void get(){                //Person p = re.getForObject("http://localhost:8080/Springmvc/rest/getPerson", Person.class);        Person p = re.postForObject("http://localhost:8080/Springmvc/rest/postPerson", new Person("hello",34),Person.class);        //re.put(url, request, urlVariables);        //re.delete(url, urlVariables);                System.out.println("call testRestTemplate  :"+p);    }

 

HttpClient的替代者 - RestTemplate

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.