MockMvcResultHandlers打印结果中文乱码解决办法

香橙派5Max + Realsense D435i + Fast-Drone-250:手把手教你搭建一个完整的无人机视觉开发环境 本文详细介绍了如何利用香橙派5Max、Realsense D435i深度相机和Fast-Drone-250项目搭建完整的无人机视觉开发环境。从硬件连接到ROS配置,再到项目部署与性能优化,提供全栈式实战指南,助力开发者快速实现SLAM算法验证和自主导航功能开发。 阅读详情

使用MockMvc测试controller接口

  • 测试主体
	@Test
    void login() throws Exception {
        String contentAsString = mockMvc.perform(MockMvcRequestBuilders
                .post(new URI("/sys/login"))
                .contentType(MediaType.APPLICATION_JSON_VALUE)
                .param("account",loginParam.getAccount())
                .param("password",loginParam.getPassword())
                .accept(MediaType.APPLICATION_JSON_VALUE))
                .andExpect(status().isOk()) 
                .andDo(print())
                .andReturn()
                .getResponse()
                .getContentAsString();
        log.info(">>> " + contentAsString);
    }
  • 打印结果
MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /sys/login
       Parameters = {}
          Headers = [Content-Type:"application/json", Accept:"application/json", Content-Length:"39"]
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = com.bbzd.pca.sys.modular.auth.controller.SysLoginController
           Method = com.bbzd.pca.sys.modular.auth.controller.SysLoginController#login(LoginParam)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.http.converter.HttpMessageNotReadableException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"application/json"]
     Content type = application/json
             Body = {"success":false,"code":1015002,"message":"请求JSONå‚æ•°æ ¼å¼ä¸æ­£ç¡®ï¼Œè¯·æ£€æŸ¥å‚æ•°æ ¼å¼"}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

解决办法

  • ResultActions拿到response再进行编码设置,getContentAsString(Charset.defaultCharset())
    @Test
    void login() throws Exception {
        String contentAsString = mockMvc.perform(MockMvcRequestBuilders
                .post(new URI("/sys/login"))
                .contentType(MediaType.APPLICATION_JSON_VALUE)
                .param("account",loginParam.getAccount())
                .param("password",loginParam.getPassword())
                .accept(MediaType.APPLICATION_JSON_VALUE))
                .andExpect(status().isOk())
                .andDo(print())   
                .andReturn()
                .getResponse()
                .getContentAsString(Charset.defaultCharset()); //防止中文乱码
        log.info(">>> " + contentAsString);
    }
Mac上VMware Fusion手动安装VMware Tools实现跨系统复制粘贴 本文详细指导了在Mac的VMware Fusion中手动安装VMware Tools的完整流程,以解决虚拟机与宿主机之间无法复制粘贴的常见问题。通过定位安装镜像、挂载、解压并运行安装脚本,最终实现跨系统无缝数据交换,提升工作效率。 阅读详情

相关推荐

计算机网络之NAT的解释与实验配置

NAT 静态NAT 动态NAT easy_ip NAT服务器映射

爱学习的JackYang的博客 1917

Spring Boot MockMvc实战:GET/POST接口测试全解析

在软件工程实践中,单元测试是保障代码质量、提升开发效率的核心环节。其原理在于通过模拟外部依赖,对代码单元进行隔离验证,从而快速定位问题。对于Spring Boot Web应用而言,针对Controller层的集成测试尤为重要,它能确保HTTP接口的输入输出符合预期。MockMvc作为Spring Test框架的关键组件,通过模拟HTTP请求与响应,无需启动完整服务器即可高效测试Web层逻辑,极大提升了测试执行速度与CI/CD集成度。本文聚焦于使用MockMvc进行GET与POST接口测试的实战场景,涵盖参数

weixin_30367873的博客 366

ICT调试技巧:从基础到实战的全面指南

本文提供了一份全面的ICT调试技巧指南,涵盖从基础认知到实战应用的全过程。详细解析了ICT设备硬件结构、程序文件构成,并重点讲解了调试界面的核心参数与高效快捷键。通过跳线、电阻、电容及二极管等常见元器件的实战调试案例,分享了参数设置要点与典型问题解决方案,帮助工程师快速掌握ICT调试核心技能,提升测试效率与准确性。

weixin_29202213的博客 342

Spring Boot 单元测试中用Mock获取数据时中文出现乱码的解决方法

Springboot单元测试时,通过MockMvcRequestBuilders.post方法 request = get("/users/") .contentType(MediaType.APPLICATION_JSON); userMvc.perform(request) .andExpect(status().isOk()) .andExpect(content().string(

gba3455的博客 2404

别再只跑Demo了!用MovieLens数据集完整复现一个电影推荐系统(Python/Pandas实战)

本文详细介绍了如何利用MovieLens数据集从零构建一个完整的电影推荐系统,涵盖数据清洗、特征工程、推荐算法实现(协同过滤和矩阵分解)以及Web服务部署的全流程。通过Python和Pandas实战,读者可以掌握推荐系统的核心技术和生产环境部署技巧,不再局限于简单的Demo运行。

weixin_29062865的博客 150

万象RK3506-EG1800网关使用说明

摘要:HD-RK3506-EG1800是一款高性能工业物联网边缘计算网关,支持Buildroot和Ubuntu双系统。文档详细介绍了网关的网络配置(包括ETH0/ETH1的静态IP设置、WiFi连接)、时钟同步、HSL软件安装配置(含开机自启动服务)、系统日志优化以及刷机操作指南(Loader/Maskrom模式)。特别提供了基于lighttpd的网页管理方案,通过HTML界面实现网络参数可视化配置,包含身份验证、实时状态显示和表单提交功能。网关默认ETH0固定IP为192.168.1.10,提供完整的CL

tian_jiangnan的博客 174

spring boot mockMvc测试用例中文乱码

创建mockMvc,增加filter。

u014723730的博客 658

idea 编译打包nacos2.0.3源码,生成可执行jar 包常见问题

idea 编译打包nacos2.0.3源码,生成可执行jar 包常见问题

fyihdg的专栏 1218

MockMvc启用Securtity验证和处理Response乱码问题

直接就启用了拦截器亏我还上百度上谷歌搜了好多帖子都不行。

骑自行车的小黄 651

37、免驱动USB双目同步测距3D活体深度检测和RV1126结合V4L开发USB摄像头使用

基本思想:需要使用双目摄像头在rv1126上进行活体检测,然后将画面实时返回到桌面上,记录一下。第二步:刷机rv1126开发板系统和ssh远程连接,见参考目录。第一步:购买可见光的红外摄像头,见参考连接,在PC端测试可用。

sxj731533730 2621

让 OData V4 界面更聪明:SAP UI5 中的 Side Effects 全解析

摘要:在OData V4应用中,字段修改常触发联动更新(Side Effects)。SAP UI5支持通过后端PATCH响应隐式返回或前端显式请求(requestSideEffects)两种方式处理。最佳实践包括:在validateFieldGroup事件中触发同批次请求,使用$$patchWithoutSideEffects避免重复刷新,并在草稿场景优化响应体。注解定义触发规则,而前端负责执行时机,二者配合可减少网络开销并保证数据一致性。Fiori elements进一步扩展了Side Effects在批

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 177

单元测试MockMvcResultHandlers.print()打印结果中body中文乱码问题处理

1、将返回的 response 使用 UTF-8编码。 ResultActions resultActions = planMvc.perform(request) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)); MockHttp

sg_knight的专栏 3544

相机图像质量评估标准全解析:MTF、CA、SNR 与色彩偏差的实战理解

图像质量评估是影像系统开发中的核心环节,它直接影响用户视觉体验与终端产品竞争力。本文基于真实的图像调试工程实践,系统讲解主流图像评价指标,包括调制传递函数(MTF)、色差(CA)、信噪比(SNR)与色彩偏差(DeltaE)等关键标准。结合 Imatest 测试流程与实际样张数据,逐项拆解各项指标在实际图像分析中的意义与优化路径,帮助开发者建立完整、量化、工程化的图像质量评估体系。

努力分享一些人工智能、计算机视觉、影像等相关的知识干货! 2806

MockMvc单元测试

原始访问层代码 package com.example.demo.web; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @Author: * @Date: 2018/...

菜鸟黑一枚 1225

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

【测试】MockMvcResultHandlers.print()打印结果中body中文乱码

使用MockMvc做controller接口测试 @Test public void test() throws Exception { //请求参数 String requestInfo = "{ \"app_key\": \"*********\", \"cust_account\": \"********\",\"product_key\": \"*****\"}"; this.mockMvc .perfor

天。朝程序猿的专栏 2289

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

HttpServletResponse PrintWriter中文乱码解决方法

HttpServletResponse PrintWriter中文乱码解决方法

qq_51021753的博客 757

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

mockMvc测试

MockMvc测试

weixin_43422437的博客 1821

springboot项目编写测试类,乱码问题解决

Spring 的 CharacterEncodingFilter ​默认只对 POST 请求生效,对 GET 请求无效。MockMvc ​默认使用 ISO-8859-1 解码响应,而服务端实际返回 UTF-8 编码数据。在test的resources中添加application.properties配置文件,添加配置。Postman 无乱码是因浏览器自动识别编码,但 MockMvc 需显式配置。在测试代码中强制覆盖编码设置。测试环境需手动强制覆盖编码设置。​MockMvc 的默认行为​。

qq_39594281的博客 299

Springboot MockMvc 单元测试 参数传值问题

Springboot MockMvc 单元测试 参数传值问题 在使用MockMvc单元测试对接口进行测试时,可能会遇到你在测试中传入的值,无法被映射到对应的属性的问题,本节就讨论一下如何解决这样的问题 其他关于接口测试的内容可以参考之前的文章: Springboot Restful风格 接口单元测试_Mock get请求 get请求参数很简单,只需要加入到param参数中,或者使用get请求将参数“?param=xxx” 拼接到url后面, MvcResult mvcResult = mockMvc.

weixin_42547243的博客 1万+

SpringBoot中SpringMVC测试框架MockMvc的使用

1.MockMvc是什么 MockMvc基于RESTful风格的SpringMVC的测试框架,我们可以测试完整的Spring MVC流程,即从URL请求到控制器处理,再到视图渲染都可以测试。 一 MockMvcBuilder MockMvcBuilder是用来构造MockMvc的构造器,其主要有两个实现:StandaloneMockMvcBuilder和DefaultMockMvcBuil...

wangxueqing52的博客 1419

Spring Boot Junit单元测试MockMvc使用

项目中使用了MockMvcRequestBuilders这个类来实现单元测试 特此举例get和post请求带Cookie,带参数,带对象,表单提交,url路径提交, 针对@ModelAttribute,@RequestBody传参传对象 获取返回对象MockHttpServletRequestBuilder MvcResult ModelAndView,返回视图/json/字符串解析 故作笔记,也方便日后查阅复习. 单元测试框必要的注入都要有,一个小的框架就出来了 @RunWith(Spr..

zhengkaiqi的博客 1679

webclient请求返回乱码

官网正常 头信息 使用链接直接访问 webclient返回页面p.getWebResponse().getContentAsString()  打印出来乱码 解决办法: p.getWebResponse().getContentAsString("utf-8") 设置编码

dandanforgetlove的专栏 2466

解决SpringBoot响应中文乱码

CharacterEncodingFilter解决中文乱码

K_arot的博客 8076

springBoot 中文乱码问题分析,即统一utf8编码

最近在使用sprintBoot,发现中文乱码问题,所以这里记录一下。 乱码问题,很多问题都要从数据库、应用程序、客户端三个部分进行分析。 1、数据库编码设置 配置my.cnf: --在 [mysqld] 标签下加上三行 default-character-set = utf8 character_set_server = utf8 lower_case_table_names = 1 //...

zzhongcy的专栏 6781

HttpClient 流式读取时中文乱码的解决方法

1、非流式读取      HttpClient中可以之间使用HttpMethod的getResponseBodyAsString()方法获取返回的内容,在读取之前,如果需要做编码设置可以这样:      HttpMethod get=new GetMethod(url);   httpClient.executeMethod(get);   get.getParams().setCon

Dream It Possible 1万+

解决SpringMVC的请求、响应中的中文乱码

1、配置tomcat(版本大于8的请忽略着一步):打开tomcat文件目录–>conf–>server.xml–>找到下面代码–.添加URIEncoding=“UTF-8”(大概在67行)————————解决Get请求中文乱码 <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/> 2、在你的springMVC项

aaasss7788的博客 638
上一篇: hostname: Unknown host 解决办法
下一篇: init datasource error, url: jdbc:mysql://localhost:3306/test 解决办法
dadeity
博客等级 码龄10年 1172粉丝 225原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dadeity

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值