1.首先我们在web项目的Controller类中添加参数为Map<String,String> map的方法:

package cn.tedu.spring.controller;import java.util.Map;import org.springframework.stereotype.Controller;
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.ResponseBody;@Controller
public class UserController {/*** 注意參數中要添加@RequestParam註解,因為此註解會獲取前端發送的所有數據;* 如果不添加,則map獲取不到數據;**method=RequestMethod.POST,produces="application/json;charset=UTF-8"可以不添加,method不指定则Post及get都能接收;*而post数据web.xml中已经添加了字符集过滤器,来指定解析方式为utf-8***********************************************************filter><filter-name>CharacterEncodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>utf-8</param-value></init-param></filter><filter-mapping><filter-name>CharacterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>************************************************************ @param map*/@RequestMapping(value="/map.do",method=RequestMethod.POST,produces="application/json;charset=UTF-8")@ResponseBodypublic void  setPOSTMap(@RequestParam Map<String,String> map){System.out.print(map);}
}

2.http post传递map 代码,此代码为网上复制
原链接为:https://blog.51cto.com/13919357/2177244

package com.fjnx.history;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;/*** HTTP工具类* 发送http/https协议get/post请求,发送map,json,xml,txt数据** @author happyqing 2016-5-20*/
public final class HttpUtil {private static Log log = LogFactory.getLog(HttpUtil.class);/*** 执行一个http/https get请求,返回请求响应的文本数据** @param url           请求的URL地址* @param queryString   请求的查询参数,可以为null* @param charset       字符集* @param pretty        是否美化* @return              返回请求响应的文本数据*/public static String doGet(String url, String queryString, String charset, boolean pretty) {StringBuffer response = new StringBuffer();HttpClient client = new HttpClient();if(url.startsWith("https")){//https请求Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443);Protocol.registerProtocol("https", myhttps);}HttpMethod method = new GetMethod(url);try {if (StringUtils.isNotBlank(queryString))//对get请求参数编码,汉字编码后,就成为%式样的字符串method.setQueryString(URIUtil.encodeQuery(queryString));client.executeMethod(method);if (method.getStatusCode() == HttpStatus.SC_OK) {BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));String line;while ((line = reader.readLine()) != null) {if (pretty)response.append(line).append(System.getProperty("line.separator"));elseresponse.append(line);}reader.close();}} catch (URIException e) {log.error("执行Get请求时,编码查询字符串“" + queryString + "”发生异常!", e);} catch (IOException e) {log.error("执行Get请求" + url + "时,发生异常!", e);} finally {method.releaseConnection();}return response.toString();}/*** 执行一个http/https post请求,返回请求响应的文本数据** @param url       请求的URL地址* @param params    请求的查询参数,可以为null* @param charset   字符集* @param pretty    是否美化* @return          返回请求响应的文本数据*/public static String doPost(String url, Map<String, String> params, String charset, boolean pretty) {StringBuffer response = new StringBuffer();HttpClient client = new HttpClient();if(url.startsWith("https")){//https请求Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443);Protocol.registerProtocol("https", myhttps);}PostMethod method = new PostMethod(url);//设置参数的字符集method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,charset);//设置post数据if (params != null) {//HttpMethodParams p = new HttpMethodParams();for (Map.Entry<String, String> entry : params.entrySet()) {//p.setParameter(entry.getKey(), entry.getValue());method.setParameter(entry.getKey(), entry.getValue());}//method.setParams(p);}try {client.executeMethod(method);if (method.getStatusCode() == HttpStatus.SC_OK) {BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));String line;while ((line = reader.readLine()) != null) {if (pretty)response.append(line).append(System.getProperty("line.separator"));elseresponse.append(line);}reader.close();}} catch (IOException e) {log.error("执行Post请求" + url + "时,发生异常!", e);} finally {method.releaseConnection();}return response.toString();}/*** 执行一个http/https post请求, 直接写数据 json,xml,txt** @param url       请求的URL地址* @param params    请求的查询参数,可以为null* @param charset   字符集* @param pretty    是否美化* @return          返回请求响应的文本数据*/public static String writePost(String url, String content, String charset, boolean pretty) {StringBuffer response = new StringBuffer();HttpClient client = new HttpClient();if(url.startsWith("https")){//https请求Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443);Protocol.registerProtocol("https", myhttps);}PostMethod method = new PostMethod(url);try {//设置请求头部类型参数//method.setRequestHeader("Content-Type","text/plain; charset=utf-8");//application/json,text/xml,text/plain//method.setRequestBody(content); //InputStream,NameValuePair[],String//RequestEntity是个接口,有很多实现类,发送不同类型的数据RequestEntity requestEntity = new StringRequestEntity(content,"text/plain",charset);//application/json,text/xml,text/plainmethod.setRequestEntity(requestEntity);client.executeMethod(method);if (method.getStatusCode() == HttpStatus.SC_OK) {BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));String line;while ((line = reader.readLine()) != null) {if (pretty)response.append(line).append(System.getProperty("line.separator"));elseresponse.append(line);}reader.close();}} catch (Exception e) {log.error("执行Post请求" + url + "时,发生异常!", e);} finally {method.releaseConnection();}return response.toString();}public static void main(String[] args) {try {String y = doGet("http://video.sina.com.cn/life/tips.html", null, "GBK", true);System.out.println(y);
//              Map params = new HashMap();
//              params.put("param1", "value1");
//              params.put("json", "{\"aa\":\"11\"}");
//              String j = doPost("http://localhost/uplat/manage/test.do?reqCode=add", params, "UTF-8", true);
//              System.out.println(j);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
package com.fjnx.history;import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;/*** author by lpp ** created at 2010-7-26 上午09:29:33 */
public class MySSLProtocolSocketFactory implements ProtocolSocketFactory {private SSLContext sslcontext = null;private SSLContext createSSLContext() {SSLContext sslcontext = null;try {// sslcontext = SSLContext.getInstance("SSL");  sslcontext = SSLContext.getInstance("TLS");sslcontext.init(null,new TrustManager[] { new TrustAnyTrustManager() },new java.security.SecureRandom());} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (KeyManagementException e) {e.printStackTrace();}return sslcontext;}private SSLContext getSSLContext() {if (this.sslcontext == null) {this.sslcontext = createSSLContext();}return this.sslcontext;}public Socket createSocket(Socket socket, String host, int port, boolean autoClose)throws IOException, UnknownHostException {return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);}public Socket createSocket(String host, int port) throws IOException, UnknownHostException {return getSSLContext().getSocketFactory().createSocket(host, port);}public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort)throws IOException, UnknownHostException {return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);}public Socket createSocket(String host, int port, InetAddress localAddress,int localPort, HttpConnectionParams params) throws IOException,UnknownHostException, ConnectTimeoutException {if (params == null) {throw new IllegalArgumentException("Parameters may not be null");}int timeout = params.getConnectionTimeout();SocketFactory socketfactory = getSSLContext().getSocketFactory();if (timeout == 0) {return socketfactory.createSocket(host, port, localAddress, localPort);} else {Socket socket = socketfactory.createSocket();SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);SocketAddress remoteaddr = new InetSocketAddress(host, port);socket.bind(localaddr);socket.connect(remoteaddr, timeout);return socket;}}// 自定义私有类  private static class TrustAnyTrustManager implements X509TrustManager {public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}public X509Certificate[] getAcceptedIssuers() {return new X509Certificate[] {};}}}

测试代码

package com.fjnx.history;import java.util.HashMap;
import java.util.Map;/*** @Author Xu Debu* @ClassName: com.fjnx.history* @Description:* @Date 2020/2/16*/
public class Test {public static void main(String[] args) {String methodUrl = "http://192.168.1.114:8089/Springmvc-responsebody/map.do";Map<String,String> map=new HashMap<>();map.put("你","好");HttpUtil.doPost(methodUrl,map,"utf-8",true);}
}

web服务端执行结果

{你=好}

24、http请求post形式发送map数据至SpringMVC的web项目中参数为map的方法相关推荐

  1. 数据可视化:在 React 项目中使用 Vega 图表 (一)

    相关包 打开搜索引擎,一搜 Vega,发现相关的包有好几个,Vega, Vega-Lite, Vega-Embed,React-Vega 等等,不免让人头晕. 别急,它们之间的关系三四句话就能说明白, ...

  2. maven mybatis mysql_Java Web学习系列——Maven Web项目中集成使用Spring、MyBatis实现对MySQL的数据访问...

    标签: 本篇内容还是建立在上一篇Java Web学习系列--Maven Web项目中集成使用Spring基础之上,对之前的Maven Web项目进行升级改造,实现对MySQL的数据访问. 添加依赖Ja ...

  3. SpringMVC,MyBatis项目中兼容Oracle和MySql的解决方案及其项目环境搭建配置、web项目中的单元测试写法、HttpClient调用post请求等案例

     要搭建的项目的项目结构如下(使用的框架为:Spring.SpingMVC.MyBatis): 2.pom.xml中的配置如下(注意,本工程分为几个小的子工程,另外两个工程最终是jar包): 其中 ...

  4. html json 访问工程,SpringBoot:Web项目中如何优雅的同时处理Json和Html请求的异常...

    在一个web项目开发中,通常都会涉及到Html和Json请求.当出现异常的时候,我们需要根据请求类型返回不同的信息.如果是Json请求,那么就返回String或者ReponseEntity类型:如果是 ...

  5. hive 导入hdfs数据_将数据加载或导入运行在基于HDFS的数据湖之上的Hive表中的另一种方法。

    hive 导入hdfs数据 Preceding pen down the article, might want to stretch out appreciation to all the well ...

  6. methods vue过滤器 和_数据动态过滤技巧在 Vue 项目中的实践

    这个问题是在下在做一个 Vue 项目中遇到的实际场景,这里记录一下我遇到问题之后的思考和最后怎么解决的(老年程序员记性不好 -.-),过程中会涉及到一些Vue源码的概念比如 $mount. rende ...

  7. xpath的数据和节点类型以及XPath中节点匹配的基本方法

    XPath数据类型  XPath可分为四种数据类型:  节点集(node-set)  节点集是通过路径匹配返回的符合条件的一组节点的集合.其它类型的数据不能转换为节点集.  布尔值(boolean)  ...

  8. 图像数据标注在自动驾驶场景中的应用及标注方法

    在人工智能计算机视觉技术中,图像数据标注是选择图像中的对象并按照名称进行标记的过程,图像数据标注有着广泛的细分应用,例如,医疗成像分析被用来提高疾病的预测.诊断和治疗:自动驾驶汽车可以准确的识别图像中 ...

  9. java发送chunked数据_如何从java servlet中的chunked响应中发送Http预告片/页脚?

    我最终为此编写了一个简单的单线程Web服务器.原来这很容易.服务器很简单.虽然代码有点粗糙,但主要的想法是存在的. 它的作用是将filecontents作为第一个块发送,并将文件的校验和作为页脚发送. ...

最新文章

  1. python学习之掷骰子游戏
  2. PythonNET网络编程3
  3. 微型计算机的典型应用场景,单片机有哪些类型和应用场景?-MCU解决方案
  4. gis环境设置在哪_三维GIS平台的可视化应用 (下)
  5. postman测试带权限接口_接口测试工具:postman
  6. 读zepto核心源码学习JS笔记(3)--zepto.init()
  7. mpc 安全多方计算协议_HashKey:说透安全多方计算 MPC 技术方案、挑战与未来
  8. 数字图像处理(21): 图像金字塔(高斯金字塔 与 拉普拉斯金字塔)
  9. 先码后看 Spring源码解析 侵立删
  10. 《缠中说禅108课》57:当下图解分析再示范
  11. LA 4487 Exclusive-OR
  12. 利安德巴赛尔任命Peter Vanacker任首席执行官;纬湃科技斩获长城汽车逆变器大额订单 | 能动...
  13. anki填空题卡片模板
  14. MyBatis一对多关系映射
  15. 蓝色——Love is Blue
  16. Vue-cli3更改项目logo图标
  17. 异构网络中基于元图的推荐——FMG
  18. linux绝育玩客云_玩客云绝育,不影响下载功能
  19. 带AI的俄罗斯方块源码
  20. 春招实习汇总(7个offer)

热门文章

  1. 朋友圈被公司“无偿征用”,该怎么办?
  2. 石油公路工程都在用的光纤测试仪是什么型号
  3. 解决ADB搜不到设备的问题
  4. android 解析json 日期格式,如何将JSON格式的日期字符串解析为日期格式
  5. opencv贾老师系列17——人脸识别实战
  6. 新品爆款打造流程与操作步骤--电商人必看
  7. Oracle同步数据到MySQL
  8. EBS杂项出库事务处理
  9. qs2021计算机专业排名,2021年QS世界大学专业排名-计算机科学与信息系统
  10. 李航《统计学习方法》学习日记【1】