Springboot学习之Http Form请求参数丢失处理

Springboot学习之Http请求参数丢失处理


前言

最近使用springboot开发一后端程序,遇到了一些奇怪的问题,今天分享一下关于参数丢失的问题,和相关的解决方案和调试手段。

且看一下demo,这是一个简单的controller,这里我使用了swaager2生成RESTful Api文档

@Controller
public class CcbHouseController {
    @ApiOperation(value = "1.1说hello")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", required = true, paramType = "form", dataType = "String")
    })
    @RequestMapping(value = "/sayhello", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String sayhello(String id) {
        Response mResponse = new Response();
        if (IsNullUtil.stringIsNull(id)) {
            return mResponse.error("参数不能为null");
        }
        return mResponse.ok("返回成功","hello");
    }
}

后端代码很简单,前端使用ajax进行请求

    $.ajax({
        type: "post",
        url: "http://127.0.0.1:8080/sayhello",
        async: true,
        data: "id=1",
        success: function(data) {

        }
    });

代码看似很简单,运行时也不会报错,但是如果在ajax请求加上contentType这个属性,很多小伙伴就会出错。

第一类错误contentType协议不正确

很多人会使用contentType:”application/json”这种协议。
错误示例:

    var postData={id:1};
    $.ajax({
        type: "post",
        url: "http://127.0.0.1:8080/sayhello",
        async: true,
        data: JSON.stringify(postData),
        contentType: "application/json",
        success: function(data) {

        }
    });

我们的后端是接收的是Form请求,这里发送的是json格式,后端肯定接收不了参数,于是报了错。
正确的应该是:

contentType: "application/x-www-form-urlencoded;charset=UTF-8",

application/x-www-form-urlencoded协议发送form请求,后端才会收到请求。
一般ajax请求不加contentType,默认是application/x-www-form-urlencoded协议。
所以前言中的代码不会报错。初学者容易犯这类错误。

第二类错误:特殊字符乱码导致参数丢失

这类错误,我在查资料时,看到一些人遇到过这类错误。这类错误多发在GET请求,参数中包含一些特殊符号。
使用encodeURIComponent可以解决,这里不详细描述,我没遇到过。机智。

主要是第三类错误,也是最难查找的一类。

第三类错误:UTF-8 BOM编码,不能被处理

这是一个同事使用c#进行作为C端,进行请求时,显现出来的问题。

问题描述:

这个同事调用我的接口,经常出现有时候能请求成功,有时候不能请求成功的问题。

刚拿到这个问题时,我查了一下日志,发现提示id参数丢失,这么短会丢失?心里一万个草泥马奔腾而过。
我立马用swagger2生成的API文档测试了一下,发现没问题啊,怎么回事?初步怀疑是同事的代码有问题。和同事沟通,查看了一下他请求的代码,并使用Fiddler进行抓包。发现一切正常。

这里就不得不说一下fiddler了,一个很好的抓包工具。但是有一个缺点,服务端的包好像抓不到。只能抓到C端的包。不知道是不是我的打开方式不对。

抓包后发现别人的请求参数没问题啊,于是心惊胆颤的查看自己的代码,也没问题啊。并且使用ajax请求也没问题。苦苦在某度上搜索了很久,没找到答案,于是准备再次抓包。这次抓服务端的包。

问题解决

于是使用了wireshark进行抓包。这个工具很强大,可以抓到请求和返回的二进制数据。
抓包结果如下

POST /sayhello HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Accept: */*
Host: 192.168.0.101:8090
Content-Length: 7
Expect: 100-continue
Connection: Keep-Alive

...id=1HTTP/1.1 200 
Content-Type: text/plain;charset=UTF-8
Content-Length: 84
Date: Tue, 10 Jul 2018 06:40:52 GMT

{"resultCode":1,"resultMsg":"...............null.........","resultType":1,"data":""}

发现请求参数前面有3个…,这3个…是什么鬼?使用二进制查看了一下,是一串ef bb bf,于是打开某度,搜索了一下出来了utf-8 bom,初步查看了一下他们的区别,原来就是当初的协议制时,搞得一个东西,很多语言,不支持此种格式。java也包含其中。

确定了问题,那就让C#端的同事去掉请求时的这个东西。

using System.Text;
var encoding = new UTF8Encoding(false);

使用这个可以去除,其它语言,请自行去除。

第四类错误:请求头Accept未设置

Accept代表客户端希望接受的数据类型
这类错误,比较容易发现,只要对比请求头即可。
解决办法:加上Accept:/ 即可。

好了,问题解决了,折腾了一两天。又可以happy的玩耍了。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Spring Boot中,接收HTTP请求参数乱码通常是由于默认字符编码不正确所致。解决该问题的方法有以下几种: 1. 使用RequestMapping或GetMapping注解的方法时,可在注解中指定produces和consumes属性,并指定字符编码。例如: ```java @RequestMapping(value = "/example", produces = "application/json;charset=UTF-8", consumes = "application/json;charset=UTF-8") public String example(@RequestBody String requestParam) { // 处理请求参数 } ``` 2. 修改Spring Boot应用的全局字符编码设置,可在application.properties或application.yml文件中配置。例如在application.properties中添加: ``` spring.http.encoding.force=true spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true ``` 3. 可以通过在Spring Boot的启动类中添加Filter或Interceptor,手动处理请求参数的字符编码。例如创建一个字符编码过滤器: ```java @Component public class CharacterEncodingFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException {} @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("UTF-8"); chain.doFilter(request, response); } @Override public void destroy() {} } ``` 通过以上方法,可以解决Spring Boot接收HTTP请求参数乱码的问题。在实际应用中,根据具体需求选择适合的解决方案。 ### 回答2: 在Spring Boot中,接收HTTP请求参数乱码的问题通常是由于字符编码不一致导致的。可以通过以下几种方式来解决: 1. 使用过滤器(Filter): 可以在Spring Boot中注册一个字符编码过滤器,通过将所有的请求和响应的字符编码都设置为UTF-8来避免乱码问题。在Spring Boot中可以通过重写WebMvcConfigurer接口中的addInterceptors方法来注册过滤器。 2. 在application.properties(application.yml)文件中设置字符编码: 可以通过在application.properties(application.yml)文件中添加以下配置来设置字符编码: spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true spring.http.encoding.force=true 3. 使用@RequestParam注解指定字符编码: 可以在Controller中的接收参数的方法上使用@RequestParam注解,并通过设置其value属性来指定字符编码。 例如: @RequestMapping("/test") public String test(@RequestParam(value = "name", required = false) String name) { // ...业务逻辑 return "success"; } 4. 在请求头中指定字符编码: 可以在发送HTTP请求时,在请求头中指定字符编码为UTF-8。例如,在使用HttpClient发送请求时,可以使用setHeader方法设置字符编码。 例如: HttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost(url); post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); // ...设置请求参数 HttpResponse response = httpClient.execute(post); 通过以上几种方式,可以解决Spring Boot接收HTTP请求参数乱码的问题。 ### 回答3: 当Spring Boot接收到HTTP请求参数乱码的情况时,可以采取以下措施解决问题。 首先,可以在Spring Boot的配置文件application.properties(或application.yml)中添加以下配置,设置请求编码格式为UTF-8: ``` spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true spring.http.encoding.force=true ``` 同时,可以使用过滤器对请求进行编码处理。在新建一个类中,实现javax.servlet.Filter接口,并重写doFilter方法: ``` import javax.servlet.*; import javax.servlet.annotation.WebFilter; import java.io.IOException; @WebFilter(filterName = "encodingFilter", urlPatterns = "/*") public class EncodingFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); chain.doFilter(request, response); } } ``` 在上述代码中,设置请求和响应的编码格式为UTF-8。 然后,可以为Spring Boot的主类添加一个注解,启用过滤器: ``` import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; @SpringBootApplication @ServletComponentScan public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 在上述代码中,使用了@SpringBootAppliaction注解标记为Spring Boot主类,并使用@ServletComponentScan注解扫描过滤器。 最后,可以在控制器中使用@RequestParam注解显式指定请求参数的编码格式。例如: ``` import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping("/hello") public String hello(@RequestParam(value = "name", required = false) String name) { if (!StringUtils.isEmpty(name)) { // 对name参数进行进一步处理 } return "Hello, " + name; } } ``` 在上述代码中,使用@RequestParam注解指定了name参数,并设置了编码格式。 通过以上措施,可以解决Spring Boot接收HTTP请求参数乱码的问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值