Feign Form表单POST提交

Form表单的POST提交,调用该类接口最长用的方式就是HttpClient,如果使用Feign,如何实现呢?

首先,看下Http中已Form的形式做Post提交的定义:

-----------------------------------华丽的分割线------------------------------------------

POST提交

HTTP 协议是以 ASCII 码传输,建立在 TCP/IP 协议之上的应用层规范。规范把 HTTP 请求分为三个部分:状态行、请求头、消息主体。类似于下面这样:

<method> <request-URL> <version>
<headers>
<entity-body>

协议规定 POST 提交的数据必须放在消息主体(entity-body)中,但协议并没有规定数据必须使用什么编码方式。实际上,开发者完全可以自己决定消息主体的格式,只要最后发送的 HTTP 请求满足上面的格式就可以。

但是,数据发送出去,还要服务端解析成功才有意义。一般服务端语言如 php、python 等,以及它们的 framework,都内置了自动解析常见数据格式的功能。服务端通常是根据请求头(headers)中的 Content-Type 字段来获知请求中的消息主体是用何种方式编码,再对主体进行解析。所以说到 POST 提交数据方案,包含了 Content-Type 和消息主体编码方式两部分。下面就正式开始介绍它们。

application/x-www-form-urlencoded   <---Form表单提交
这应该是最常见的 POST 提交数据的方式了。浏览器的原生 form 表单,如果不设置 enctype 属性,那么最终就会以 application/x-www-form-urlencoded 方式提交数据。请求类似于下面这样(无关的请求头在本文中都省略掉了):

POST http://www.example.com HTTP/1.1
Content-Type: application/x-www-form-urlencoded;charset=utf-8
title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3

首先,Content-Type 被指定为 application/x-www-form-urlencoded;
其次,提交的数据按照 key1=val1&key2=val2 的方式进行编码,key 和 val 都进行了 URL 转码。
大部分服务端语言都对这种方式有很好的支持。例如 PHP 中,$_POST[‘title’] 可以获取到 title 的值,$_POST[‘sub’] 可以得到 sub 数组。
很多时候,我们用 Ajax 提交数据时,也是使用这种方式。例如 JQuery 和 QWrap 的 Ajax,Content-Type 默认值都是「application/x-www-form-urlencoded;charset=utf-8」。

multipart/form-data
这又是一个常见的 POST 数据提交的方式。我们使用表单上传文件时,必须让 form 的 enctyped 等于这个值。
这种方式一般用来上传文件,各大服务端语言对它也有着良好的支持。

上面提到的这两种 POST 数据的方式,都是浏览器原生支持的,而且现阶段原生 form 表单也只支持这两种方式。

但是随着越来越多的 Web 站点,尤其是 WebApp,全部使用 Ajax 进行数据交互之后,我们完全可以定义新的数据提交方式,给开发带来更多便利。

application/json
application/json 这个 Content-Type 作为响应头大家肯定不陌生。实际上,现在越来越多的人把它作为请求头,用来告诉服务端消息主体是序列化后的 JSON 字符串。由于 JSON 规范的流行,除了低版本 IE 之外的各大浏览器都原生支持 JSON.stringify,服务端语言也都有处理 JSON 的函数,使用 JSON 不会遇上什么麻烦。

POST http://www.example.com HTTP/1.1
Content-Type: application/json;charset=utf-8
{"title":"test","sub":[1,2,3]}

text/xml
它是一种使用 HTTP 作为传输协议,XML 作为编码方式的远程调用规范。
XML-RPC 协议简单、功能够用,各种语言的实现都有。它的使用也很广泛,如 WordPress 的 XML-RPC Api,搜索引擎的 ping 服务等等。JavaScript 中,也有现成的库支持以这种方式进行数据交互,能很好的支持已有的 XML-RPC 服务。不过,我个人觉得 XML 结构还是过于臃肿,一般场景用 JSON 会更灵活方便。

-----------------------------------华丽的分割线------------------------------------------

通过上面对POST提交的简单介绍,对Post提交Form表单已经有了认识:

1、Content-Type 被指定为 application/x-www-form-urlencoded;

2、提交的数据按照 key1=val1&key2=val2 的方式进行编码,key 和 val 都进行了 URL 转码

Feign代码实现样例1

@FeignClient(name = "authentication", url = "${feign.url.authentication}")
public interface AuthenticationService {
    @RequestMapping(value = "/authentication/idcard_internal_apply",
            method = RequestMethod.POST,
            consumes = "application/x-www-form-urlencoded;charset=UTF-8")
    RealNameResponse verify(String entityBody);
}

测试调用:

@RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持
@SpringBootTest(classes = MasApplication.class)
public class NewMyTest {
    @Autowired
    private AuthenticationService authenticationService;

    @Test
    public void testRealName() throws Exception {
        Map<String, String> reqParms =  new HashMap<>();
        reqParms.put("merchantNo", "245888");
        reqParms.put("idNo", "310123198901233456");
        reqParms.put("realName", "李大庄");
        reqParms.put("merchantOrderNo", DateUtil.format(new Date(), DateUtil.longFormat));
        reqParms.put("reqSource", "ZF952_API");
        //===========拼装数据为:k=v&k=v 格式===========
        StringBuffer v=new StringBuffer();
        for(Map.Entry<String, String> entries: reqParms.entrySet()){
            v.append(entries.getKey()).append("=").append(entries.getValue()).append("&");
        }
        System.out.println("---------------"+v.substring(0,v.length()-1));
        RealNameResponse response = authenticationService.verify(v.substring(0,v.length()-1));
        System.out.println("RESPONSE--------------->"+response);
    }
}

很明显代码有点挫,先构建了Map对象,然后遍历拼装k=v&k=v格式数据,是否可以直接支持Map数据的传参呢,当然可以

Feign代码实现样例2

/**
 * Description: Form表单提交
 *
 * @author: lishaohua
 * @date: 2018/5/28  9:50
 */
@ConfigurationProperties("feign")
public class FeignFormConfiguration {
    private Integer connectionTimeout = 5000;
    private Integer readTimeout = 10000;
    private Integer retry = 0;
    private Long period = 100L;
    private Long maxPeriod = 1000L;

    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

    @Bean
    @Scope("prototype")
    public Encoder feignFormEncoder() {
        Encoder encoder = new FormEncoder(new SpringEncoder(this.messageConverters));
        return encoder;
    }


    public Request.Options feignOptions() {
        return new Request.Options(connectionTimeout, readTimeout);
    }

    public Retryer feignRetryer() {
        if (retry > 0) {
            // the first call is also one attempt try
            return new Retryer.Default(period, maxPeriod, retry + 1);
        } else {
            return Retryer.NEVER_RETRY;
        }
    }

    public Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

    public Integer getConnectionTimeout() {
        return connectionTimeout;
    }

    public void setConnectionTimeout(Integer connectionTimeout) {
        this.connectionTimeout = connectionTimeout;
    }

    public Integer getReadTimeout() {
        return readTimeout;
    }

    public void setReadTimeout(Integer readTimeout) {
        this.readTimeout = readTimeout;
    }

    public Integer getRetry() {
        return retry;
    }

    public void setRetry(Integer retry) {
        this.retry = retry;
    }

    public Long getPeriod() {
        return period;
    }

    public void setPeriod(Long period) {
        this.period = period;
    }

    public Long getMaxPeriod() {
        return maxPeriod;
    }

    public void setMaxPeriod(Long maxPeriod) {
        this.maxPeriod = maxPeriod;
    }
}
@FeignClient(name = "authentication", url = "${feign.url.authentication}",
        configuration = FeignFormConfiguration.class)
public interface AuthenticationService {
    @RequestMapping(value = "/authentication/idcard_internal_apply",
            method = RequestMethod.POST,
            consumes = "application/x-www-form-urlencoded;charset=UTF-8")
    RealNameResponse verify(Map<String,?> entityBody);
}

测试

@RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持
@SpringBootTest(classes = MasApplication.class)
public class NewMyTest {
    @Autowired
    private AuthenticationService authenticationService;

    @Test
    public void testRealName() throws Exception {
        Map<String, String> reqParms =  new HashMap<>();
        reqParms.put("merchantNo", "245888");
        reqParms.put("idNo", "310123198901233456");
        reqParms.put("realName", "李大庄");
        reqParms.put("merchantOrderNo", DateUtil.format(new Date(), DateUtil.longFormat));
        reqParms.put("reqSource", "ZF952_API");
       
        RealNameResponse response = authenticationService.verify(reqParms);
        System.out.println("RESPONSE--------------->"+response);
    }
}

为了更好的理解POST提交后各个参数的含义,建议使用大白鲨抓包。。。。

参考文章:

四种常见的POST提交方式

猜你喜欢

转载自www.cnblogs.com/huahua035/p/9100283.html