欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot RestTemplate GET POST请求的实例讲解

程序员文章站 2022-06-17 20:51:17
一)resttemplate简介resttemplate是http客户端库提供了一个更高水平的api。主要用于rest服务调用。resttemplate方法: 方法组...

一)resttemplate简介

resttemplate是http客户端库提供了一个更高水平的api。主要用于rest服务调用。

resttemplate方法:

方法组 描述

getforobject

通过get检索表示形式。

getforentity

responseentity通过使用get 检索(即状态,标头和正文)。

headforheaders

通过使用head检索资源的所有标头。

postforlocation

通过使用post创建新资源,并location从响应中返回标头。

postforobject

通过使用post创建新资源,并从响应中返回表示形式。

postforentity

通过使用post创建新资源,并从响应中返回表示形式。

put

通过使用put创建或更新资源。

patchforobject

通过使用patch更新资源,并从响应中返回表示形式。请注意,jdk httpurlconnection不支持patch,但是apache httpcomponents和其他支持。

delete

使用delete删除指定uri处的资源。

optionsforallow

通过使用allow检索资源的允许的http方法。

exchange

前述方法的通用性强(且意见少的版本),在需要时提供了额外的灵活性。它接受requestentity(包括http方法,url,标头和正文作为输入)并返回responseentity。

这些方法允许使用parameterizedtypereference而不是class使用泛型来指定响应类型。

execute

执行请求的最通用方法,完全控制通过回调接口进行的请求准备和响应提取。

二)resttemplate案例

第一步:创建一个maven项目,在pom.xml引入一个springboot的版本

pom.xml内容:

<project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelversion>4.0.0</modelversion>
  <groupid>com.oysept</groupid>
  <artifactid>spring_resttemplate</artifactid>
  <version>0.0.1-snapshot</version>
  <packaging>jar</packaging>
 
  <parent>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-parent</artifactid>
    <version>2.1.4.release</version>
    <relativepath/>
  </parent>
 
  <dependencies>
    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-web</artifactid>
    </dependency>
  </dependencies>
  
  <build>
    <plugins>
      <plugin>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-maven-plugin</artifactid>
        <configuration>
          <mainclass>com.oysept.resttemplateapplication</mainclass>
        </configuration>
      </plugin>
      <plugin>
        <groupid>org.apache.tomcat.maven</groupid>
        <artifactid>tomcat7-maven-plugin</artifactid>
      </plugin>
    </plugins>
  </build>
</project>

application.yml配置:该配置就一个默认端口

server:

port: 8080

创建一个springboot启动类resttemplateapplication

package com.oysept;
 
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.boot.builder.springapplicationbuilder;
 
@springbootapplication
public class resttemplateapplication {
 
  public static void main(string[] args) {
    new springapplicationbuilder(resttemplateapplication.class).run(args);
  }
}

到此步骤时,可以先运行resttemplateapplication中的main方法,检验springboot启动是否正常。

第二步:创建一个resttemplate配置类并注入,因为在使用时,不提前注入restttemplate,在通过@autowired使用会报resttemplate找不到

package com.oysept.config;
 
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.web.client.resttemplate;
 
/**
 * 注册一个resttemplate bean, 否则直接通过@autowired使用会报resttemplate找不到
 * @author ouyangjun
 */
@configuration
public class resttemplateconfig {
 
  /**
   * 方式一: 默认是使用jdk原生java.net.httpurlconnection请求
   * @return
   */
  @bean(name = "resttemplate")
  public resttemplate resttemplate() {
    return new resttemplate();
  }
 
  /**
   * 方式二: 使用apache http内置请求, 需要在pom.xml中引入相应的apache jar
   * 可以使用httpclient,设置一些http连接池等信息
   * @return
   *
  @bean(name = "resttemplate")
  public resttemplate resttemplate() {
    return new resttemplate(new httpcomponentsclienthttprequestfactory());
  }
   */
 
  /**
   * 方式三: 使用okhttp内置请求, 需要在pom.xml中引入相应的okhttp3 jar
   * 可以使用okhttpclient,设置一些http连接池信息
   * @return
   *
  @bean(name = "resttemplate")
  public resttemplate resttemplate() {
    return new resttemplate(new okhttp3clienthttprequestfactory());
  }
  */
}

第三步:创建一个vo类,用于测试入参和出参

package com.oysept.vo; 
public class msgvo { 
  private string msgkey;
  private string msgvalue;
 
  public string getmsgkey() {return msgkey;}
  public void setmsgkey(string msgkey) {this.msgkey = msgkey;}
 
  public string getmsgvalue() {return msgvalue;}
  public void setmsgvalue(string msgvalue) {this.msgvalue = msgvalue;}
 
  public string tostring() {
    return "msgvo [msgkey: "+this.msgkey+", msgvalue: "+this.msgvalue+"]";
  }
}

第四步:创建一个服务端接口,用于测试

package com.oysept.controller;
 
import java.util.arraylist;
import java.util.list; 
import org.springframework.http.mediatype;
import org.springframework.web.bind.annotation.pathvariable;
import org.springframework.web.bind.annotation.requestbody;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.bind.annotation.requestparam;
import org.springframework.web.bind.annotation.restcontroller;
 
import com.oysept.vo.msgvo;
 
/**
 * 服务端, 提供接口被调用
 * @author ouyangjun
 */
@restcontroller
public class servercontroller {
 
  // 无参get请求: http://localhost:8080/server/get
  @requestmapping(value = "/server/get", method = requestmethod.get)
  public string get() {
    return "/server/get";
  }
 
  // 带参get请求: http://localhost:8080/server/get/param?param=111222333444
  @requestmapping(value = "/server/get/param", method = requestmethod.get)
  public string getparam(@requestparam(value = "param") string param) {
    return "/server/get/param," + param;
  }
 
  // 路径中带参get请求: http://localhost:8080/server/get/url/aaaa/bbbb
  @requestmapping(value = "/server/get/url/{one}/{two}", method = requestmethod.get)
  public string geturl(@pathvariable("one") string one, @pathvariable("two") string two) {
    return "/get/url/{one}/{two}," + one + "," + two;
  }
 
  // 无参get请求, 返回list: http://localhost:8080/server/get/list
  @requestmapping(value = "/server/get/list", method = requestmethod.get)
  public list<object> getlist() {
    list<object> list = new arraylist<object>();
    list.add(11);
    list.add("aa");
    return list;
  }
 
  // 无参get请求, 返回对象: http://localhost:8080/server/get/msgvo
  @requestmapping(value = "/server/get/msgvo", method = requestmethod.get)
  public msgvo getmsgvo() {
    msgvo vo = new msgvo();
    vo.setmsgkey("keyaaa");
    vo.setmsgvalue("valuebbb");
    return vo;
  }
 
  // post请求, 表单参数, application/x-www-form-urlencoded
  @requestmapping(value = "/server/post/form", method = requestmethod.post, 
    consumes = mediatype.application_form_urlencoded_value)
  public msgvo postform(msgvo msgvo) {
    system.out.println("msgkey: " + msgvo.getmsgkey() + ", msgvalue: " + msgvo.getmsgvalue());
    return msgvo;
  }
 
  // post请求, json参数, application/json
  @requestmapping(value = "/server/post/json", method = requestmethod.post, 
      consumes = mediatype.application_json_utf8_value,
      produces = mediatype.application_json_utf8_value)
  public msgvo postjson(@requestbody msgvo msgvo) {
    system.out.println("msgkey: " + msgvo.getmsgkey() + ", msgvalue: " + msgvo.getmsgvalue());
    return msgvo;
  }
}

第五步:创建一个测试服务端接口的api

import的类和注入的resttemplate:

package com.oysept.controller; 
import java.net.uri;
import java.util.hashmap;
import java.util.list;
import java.util.map;
 
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.beans.factory.annotation.qualifier;
import org.springframework.http.httpentity;
import org.springframework.http.httpheaders;
import org.springframework.http.mediatype;
import org.springframework.http.requestentity;
import org.springframework.http.responseentity;
import org.springframework.util.linkedmultivaluemap;
import org.springframework.util.multivaluemap;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.bind.annotation.restcontroller;
import org.springframework.web.client.resttemplate;
import org.springframework.web.util.uricomponentsbuilder;
 
import com.oysept.vo.msgvo;
 
/**
 * 客户端, 调用服务端提供的接口
 * @author ouyangjun
 */
@restcontroller
public class clientcontroller {
 
  // 使用默认请求方式
  @autowired
  @qualifier(value = "resttemplate")
  private resttemplate resttemplate;
 
  // 在此处添加客户端测试代码
}

1、get请求

// 直接在浏览中输入访问地址: http://localhost:8080/client/get
@requestmapping(value = "/client/get", method = requestmethod.get)
public string get() {
  // 无参get请求
  string get = resttemplate.getforobject("http://localhost:8080/server/get", string.class);
  system.out.println("==>/server/get return: " + get);
 
  // 带参get请求
  string getparam = resttemplate.getforobject("http://localhost:8080/server/get/param?param=111222333444", string.class);
  system.out.println("==>/server/get/param return: " + getparam);
 
  // 带参get url请求
  string geturlparam = resttemplate.getforobject("http://localhost:8080/server/get/url/{one}/{two}", string.class, "aaaa", "bbbb");
  system.out.println("==>/server/get/url/{one}/{two} return: " + geturlparam);
 
  // 带参get url请求
  map<string, string> vars = new hashmap<string, string>();
  vars.put("one", "hhhh");
  vars.put("two", "eeee");
  string geturlvars = resttemplate.getforobject("http://localhost:8080/server/get/url/{one}/{two}", string.class, vars);
  system.out.println("==>/server/get/url/{one}/{two} return: " + geturlvars);
 
  // 无参get请求, 返回list
  @suppresswarnings("unchecked")
  list<string> getlist = resttemplate.getforobject("http://localhost:8080/server/get/list", list.class);
  system.out.println("==>/server/get/list return: " + getlist);
 
  // get请求, 返回对象
  responseentity<msgvo> entity = resttemplate.getforentity("http://localhost:8080/server/get/msgvo", msgvo.class);
  system.out.println("==>/server/get/list return: " + entity.getbody());
  return "get success";
}

2、get url中传参请求

// 直接在浏览中输入访问地址: http://localhost:8080/client/get/request
// get请求, url参数, 在表头中添加参数
@requestmapping(value = "/client/get/request", method = requestmethod.get)
public string getrequest() {
  // url中参数
  map<string, string> vars = new hashmap<string, string>();
  vars.put("one", "hhhh");
  vars.put("two", "eeee");
 
  // 请求地址
  string uritemplate = "http://localhost:8080/server/get/url/{one}/{two}";
  // 给url地址encode转码
  uri uri = uricomponentsbuilder.fromuristring(uritemplate).buildandexpand(vars).touri();
  // get请求参数
  requestentity<void> requestentity = 
        requestentity.get(uri)
        .header("myheader", "aaabbbcccddd")
        .build();
  // 响应
  responseentity<string> response = resttemplate.exchange(requestentity, string.class);
  // 结果
  system.out.println("==>/get/request header: " + response.getheaders().getfirst("myheader"));
  system.out.println("==>/get/request body: " + response.getbody());
  return "post success";
}

3、post application/x-www-form-urlencoded表单传参请求

// 直接在浏览中输入访问地址: http://localhost:8080/client/postform
// post请求, form表单入参
@requestmapping(value = "/client/postform", method = requestmethod.get)
public string postform() {
  // uri
  string uritemplate = "http://localhost:8080/server/post/form";
 
  // 设置请求头为form形式: application/x-www-form-urlencoded
  httpheaders headers = new httpheaders();
  headers.setcontenttype(mediatype.application_form_urlencoded);
 
  // 设置参数, 和msgvo中变量名对应
  multivaluemap<string, string> map = new linkedmultivaluemap<string, string>();
  map.add("msgkey", "1234");
  map.add("msgvalue", "testtest");
 
  // 封装请求参数
  httpentity<multivaluemap<string, string>> requestb = new httpentity<multivaluemap<string, string>>(map,
  headers);
  responseentity<string> response = resttemplate.postforentity(uritemplate, requestb, string.class);
  system.out.println("==>/server/post/form return: " + response.getbody());
  return "post success";
}

4、post application/json json传参请求

// 直接在浏览中输入访问地址: http://localhost:8080/client/postjson
// post请求, json入参
@requestmapping(value = "/client/postjson", method = requestmethod.get)
public string postjson() {
  // json入参
  msgvo vo = new msgvo();
  vo.setmsgkey("ttt");
  vo.setmsgvalue("kkk");
 
  string uritemplate = "http://localhost:8080/server/post/json";
  uri uri = uricomponentsbuilder.fromuristring(uritemplate).buildandexpand().touri();
 
  requestentity<msgvo> requestentity = 
      requestentity.post(uri)
      .header("content-type", "application/json; charset=utf-8")
      .body(vo);
  
  responseentity<msgvo> response = resttemplate.exchange(requestentity, msgvo.class);
  system.out.println("==>/server/post/json return: " + response.getbody());
  return "post success";
}

项目结构图:

SpringBoot RestTemplate GET POST请求的实例讲解

以上这篇springboot resttemplate get post请求的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。