Java使用x-www-form-urlencoded发请求

平常在开发过程中用的最多的就是JSON格式,请求编码就是 application/json,但偏偏有些接口是 x-www-form-urlencoded,怎么办呢,重新封装喽
在POSTMan工具是叫 x-www-form-urlencoded
在 APIpost工具中是叫 urlencoded
在这里插入图片描述

Map<String, String> request = new HashMap<>();request.put("username", "xxx");request.put("password", "xxx");String result = HttpRequestUtil.post(request, "http://xxxx", new HashMap<String, String>(), "application/x-www-form-urlencoded");System.out.println(result);
package utils;import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;import com.alibaba.fastjson.JSONObject;/***    * @ClassName:HttpRequestUtil   * @Description: Http请求  */
public class HttpRequestUtil {private String defaultContentEncoding;public HttpRequestUtil() {this.defaultContentEncoding = Charset.defaultCharset().name();}/*** 默认的响应字符集*/public String getDefaultContentEncoding() {return this.defaultContentEncoding;}/*** 设置默认的响应字符集*/public void setDefaultContentEncoding(String defaultContentEncoding) {this.defaultContentEncoding = defaultContentEncoding;}public static String post(JSONObject json, String url) throws Exception{CloseableHttpClient httpclient = HttpClientBuilder.create().build();HttpPost post = new HttpPost(url);CloseableHttpResponse  response = null;InputStream in = null;BufferedReader br = null;String result = "";try {StringEntity s = new StringEntity(json.toString(),"utf-8");s.setContentEncoding("UTF-8");/*发送json数据需要设置contentType*/s.setContentType("application/json");post.setEntity(s);post.setHeader("Content-Type","application/json;charset=utf-8");response = httpclient.execute(post);in = response.getEntity().getContent();br = new BufferedReader(new InputStreamReader(in, "utf-8"));StringBuilder strber= new StringBuilder();String line = null;while((line = br.readLine())!=null){strber.append(line+'\n');}result = strber.toString();if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){if(StringUtils.isBlank(result)) result = "服务器异常";throw new Exception(result);}// System.out.println("返回数据="+result);} catch (Exception e) {//System.err.println("调用接口出错::::::::::::"+e.getMessage());throw new Exception(e.getMessage());} finally {if(null != br) br.close();if(null != br) in.close();if(null != response) response.close();if(null != httpclient) httpclient.close();}return result;}public static String post(JSONObject json, String url, Map<String, String> headerMap) throws Exception{CloseableHttpClient httpclient = HttpClientBuilder.create().build();HttpPost post = new HttpPost(url);CloseableHttpResponse  response = null;InputStream in = null;BufferedReader br = null;String result = "";try {StringEntity s = new StringEntity(json.toString(),"utf-8");s.setContentEncoding("UTF-8");/*发送json数据需要设置contentType*/s.setContentType("application/json");post.setEntity(s);post.setHeader("Content-Type","application/json;charset=utf-8");Set<Entry<String, String>> headerEntries = headerMap.entrySet();for (Entry<String, String> headerEntry:headerEntries){post.setHeader(headerEntry.getKey(), headerEntry.getValue());}response = httpclient.execute(post);in = response.getEntity().getContent();br = new BufferedReader(new InputStreamReader(in, "utf-8"));StringBuilder strber= new StringBuilder();String line = null;while((line = br.readLine())!=null){strber.append(line+'\n');}result = strber.toString();if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){if(StringUtils.isBlank(result)) result = "服务器异常";throw new Exception(result);}//System.out.println("返回数据="+result);} catch (Exception e) {//System.err.println("调用接口出错::::::::::::"+e.getMessage());throw new Exception(e.getMessage());} finally {br.close();in.close();response.close();httpclient.close();}return result;}/*** ContentType.URLENCODED.getHeader()* @param map* @param url* @param headerMap* @param contentType* @return* @throws Exception*/public static String post(Map<String, String> map, String url, Map<String, String> headerMap, String contentType) throws Exception{CloseableHttpClient httpclient = HttpClientBuilder.create().build();HttpPost post = new HttpPost(url);CloseableHttpResponse  response = null;InputStream in = null;BufferedReader br = null;String result = "";try {List<NameValuePair> nameValuePairs = getNameValuePairList(map);UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");/*发送json数据需要设置contentType*/urlEncodedFormEntity.setContentType(contentType);post.setEntity(urlEncodedFormEntity);post.setHeader("Content-Type", contentType);Set<Entry<String, String>> headerEntries = headerMap.entrySet();for (Entry<String, String> headerEntry:headerEntries){post.setHeader(headerEntry.getKey(), headerEntry.getValue());}response = httpclient.execute(post);in = response.getEntity().getContent();br = new BufferedReader(new InputStreamReader(in, "utf-8"));StringBuilder strber= new StringBuilder();String line = null;while((line = br.readLine())!=null){strber.append(line+'\n');}result = strber.toString();if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){if(StringUtils.isBlank(result)) result = "服务器异常";throw new Exception(result);}//System.out.println("返回数据="+result);} catch (Exception e) {//System.err.println("调用接口出错::::::::::::"+e.getMessage());throw new Exception(e.getMessage());} finally {br.close();in.close();response.close();httpclient.close();}return result;}private static List<NameValuePair> getNameValuePairList(Map<String, String> map) {List<NameValuePair> list = new ArrayList<>();for(String key : map.keySet()) {list.add(new BasicNameValuePair(key,map.get(key)));}return list;}public static String post(String params, String url, Map<String, String> headerMap) throws Exception{CloseableHttpClient httpclient = HttpClientBuilder.create().build();HttpPost post = new HttpPost(url);CloseableHttpResponse  response = null;InputStream in = null;BufferedReader br = null;String result = "";try {StringEntity s = new StringEntity(params.toString(),"utf-8");s.setContentEncoding("UTF-8");/*发送json数据需要设置contentType*/s.setContentType("application/json");post.setEntity(s);post.setHeader("Content-Type","application/json;charset=utf-8");Set<Entry<String, String>> headerEntries = headerMap.entrySet();for (Entry<String, String> headerEntry:headerEntries){post.setHeader(headerEntry.getKey(), headerEntry.getValue());}response = httpclient.execute(post);in = response.getEntity().getContent();br = new BufferedReader(new InputStreamReader(in, "utf-8"));StringBuilder strber= new StringBuilder();String line = null;while((line = br.readLine())!=null){strber.append(line+'\n');}result = strber.toString();if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){if(StringUtils.isBlank(result)) result = "服务器异常";throw new Exception(result);}//System.out.println("返回数据="+result);} catch (Exception e) {//System.err.println("调用接口出错::::::::::::"+e.getMessage());throw new Exception(e.getMessage());} finally {br.close();in.close();response.close();httpclient.close();}return result;}public static String put(JSONObject json, String url, Map<String, String> headerMap) throws Exception {CloseableHttpClient httpclient = HttpClientBuilder.create().build();HttpPut post = new HttpPut(url);CloseableHttpResponse  response = null;InputStream in = null;BufferedReader br = null;String result = "";try {StringEntity s = new StringEntity(json.toString(),"utf-8");s.setContentEncoding("UTF-8");/*发送json数据需要设置contentType*/s.setContentType("application/json");post.setEntity(s);post.setHeader("Content-Type","application/json;charset=utf-8");Set<Entry<String, String>> headerEntries = headerMap.entrySet();for (Entry<String, String> headerEntry:headerEntries){post.setHeader(headerEntry.getKey(), headerEntry.getValue());}response = httpclient.execute(post);in = response.getEntity().getContent();br = new BufferedReader(new InputStreamReader(in, "utf-8"));StringBuilder strber= new StringBuilder();String line = null;while((line = br.readLine())!=null){strber.append(line+'\n');}result = strber.toString();if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){if(StringUtils.isBlank(result)) result = "服务器异常";throw new Exception(result);}//System.out.println("返回数据="+result);} catch (Exception e) {//System.err.println("调用接口出错::::::::::::"+e.getMessage());throw new Exception(e.getMessage());} finally {br.close();in.close();response.close();httpclient.close();}return result;}public static String delete(String url, Map<String, String> headerMap) throws Exception {CloseableHttpClient httpclient = HttpClientBuilder.create().build();HttpDelete post = new HttpDelete(url);CloseableHttpResponse  response = null;InputStream in = null;BufferedReader br = null;String result = "";try {post.setHeader("Content-Type","application/json;charset=utf-8");Set<Entry<String, String>> headerEntries = headerMap.entrySet();for (Entry<String, String> headerEntry:headerEntries){post.setHeader(headerEntry.getKey(), headerEntry.getValue());}response = httpclient.execute(post);in = response.getEntity().getContent();br = new BufferedReader(new InputStreamReader(in, "utf-8"));StringBuilder strber= new StringBuilder();String line = null;while((line = br.readLine())!=null){strber.append(line+'\n');}result = strber.toString();if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){if(StringUtils.isBlank(result)) result = "服务器异常";throw new Exception(result);}//System.out.println("返回数据="+result);} catch (Exception e) {//System.err.println("调用接口出错::::::::::::"+e.getMessage());throw new Exception(e.getMessage());} finally {br.close();in.close();response.close();httpclient.close();}return result;}public static String get(JSONObject paramsObj, String url, Map<String, String> headerMap) throws Exception {CloseableHttpClient httpclient = HttpClientBuilder.create().build();CloseableHttpResponse  response = null;InputStream in = null;BufferedReader br = null;String result = "";try {StringBuffer param = new StringBuffer();int i = 0;Set<Entry<String, Object>> entries = paramsObj.entrySet();for (Entry<String, Object> entry:entries){if (i == 0)param.append("?");elseparam.append("&");param.append(entry.getKey()).append("=").append(entry.getValue());i++;}url += param;HttpGet post = new HttpGet(url);
//            post.setHeader("Content-Type","application/json;charset=utf-8");Set<Entry<String, String>> headerEntries = headerMap.entrySet();for (Entry<String, String> headerEntry:headerEntries){post.setHeader(headerEntry.getKey(), headerEntry.getValue());}response = httpclient.execute(post);in = response.getEntity().getContent();br = new BufferedReader(new InputStreamReader(in, "utf-8"));StringBuilder strber= new StringBuilder();String line = null;while((line = br.readLine())!=null){strber.append(line+'\n');}result = strber.toString();if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){if(StringUtils.isBlank(result)) result = "服务器异常";throw new Exception(result);}//System.out.println("返回数据="+result);} catch (Exception e) {// System.err.println("调用接口出错::::::::::::"+e.getMessage());throw new Exception(e.getMessage());} finally {br.close();in.close();response.close();httpclient.close();}return result;}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/159646.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Spring Boot 邮件发送(五种类型的邮件)

邮件协议&#xff1a; SMTP、POP3、IMAP SMTP 协议全称为 Simple Mail Transfer Protocol&#xff0c;译作简单邮件传输协议&#xff0c;它定义了邮件客户端软件与 SMTP 服务器之间&#xff0c;以及 SMTP 服务器与 SMTP 服务器之间的通信规则。 用户先将邮件投递到腾讯的 SMT…

论文阅读 Forecasting at Scale (一)

最近在看时间序列的文章&#xff0c;回顾下经典 论文地址 项目地址 Forecasting at Scale 摘要1、介绍2、时间业务序列的特点3、Prophet预测模型3.1、趋势模型3.1.1、非线性饱和增长3.1.2、具有变化点的线性趋势3.1.3、自动转换点选择3.1.4、趋势预测的不确定性 摘要 预测是一…

暗物质探测器认知教学VR元宇宙平台打破传统束缚

“飞船正在上升&#xff0c;马上就冲出大气层了!”这是一位在1&#xff1a;1还原的神舟飞船返回舱内借助VR设备置身元宇宙世界&#xff0c;沉浸式体验升空全过程的游客兴奋地说道。不仅如此&#xff0c;在载人飞船训练期&#xff0c;元宇宙技术为航天员虚拟一个逼真的太空世界&…

vue3 iconify 图标几种使用 并加载本地 svg 图标

iconify iconify 与 iconify/vue 使用 下载 pnpm add iconify/vue -D使用 import { Icon } from "iconify/vue";<template><Icon icon"mdi-light:home" style"color: red; font-size: 43px" /><Icon icon"mdi:home-flo…

shell脚本三

目录 一、循环语句 一、循环 二、for循环语句 1.列表循环 2.与c语言循环相似的for循环 3.使用for打印三角形以及乘法表 4.测试172.16.114.0网段存活的主机并将存活的主机IP地址写入文件中&#xff0c;未存活的主机放入另一文件中 三、while循环语句 四、until循环语句…

如何使用 Navicat 连接 GaussDB 主备版

Navicat Premium&#xff08;16.2.8 Windows版或以上&#xff09; 已支持对GaussDB 主备版的管理和开发功能。它不仅具备轻松、便捷的可视化数据查看和编辑功能&#xff0c;还提供强大的高阶功能&#xff08;如模型、结构同步、协同合作、数据迁移等&#xff09;&#xff0c;这…

每日一练:质因数分解

1. 题目 从键盘输入一个整数&#xff0c;开始整数的质因数分解&#xff0c;最后打印出该整数的所有质因数。 2.解题思路 1&#xff09;初始化&#xff1a; 从最小的质数开始&#xff0c;将输入的整数不断除以质数&#xff0c;直到无法整除为止。   2&#xff09;循环&#x…

ansible的基本安装

目录 一、简介 1.ansible自动化运维人工运维时代 2.自动化运维时代 3.ansible介绍 4.ansible特点 二、ansible实践 1.环境 2.ansible管理安装 3.ansible被管理安装 4.管理方式 5.添加被管理机器的ip 6.ssh密码认证方式管理 三、配置免密登录 1.ansible自带的密码…

【grep】从html表格中快速定位某个数据

文章目录 1 背景2 参考知识2.1 grep2.2 HTML基础语言标签 3 解决方案 1 背景 在html中是一堆表格、图片、文字什么的&#xff0c;想从表格中提取关键词为“GJC”后对应的数字&#xff0c;怎么办呢&#xff1f; 逐个打开html文件&#xff0c;“ctrlF”搜一下&#xff0c;然后复…

vue项目中element-ui对话框el-dialog嵌套显示时多了一个遮罩层解决办法

在对话框里又嵌套了一个对话框展示时&#xff0c;多了一个遮罩层&#xff0c;如下图所示&#xff1a; 解决办法如下&#xff1a; 给对话框添加append-to-body 属性&#xff0c;参考以下代码&#xff1a; <el-dialog :visible.sync"dialogVisible" append-to-body …

所有产品都值得用AI再做一遍,让AGI与品牌营销双向奔赴

微软 CEO Satya Nadella 曾经说过&#xff1a;“所有的产品都值得用 AI 重做一遍。” AI 大模型的出现&#xff0c;开启了一个全新的智能化时代&#xff0c;重新定义了人机交互。这让生成式 AI 技术变得「触手可得」&#xff0c;也让各行业看到 AGI 驱动商业增长的更大可能性。…

ui设计师简历自我评价的范文(合集)

ui设计师简历自我评价的范文篇一 本人毕业于艺术设计专业&#xff0c;具有较高的艺术素养&#xff0c;平时注重设计理论知识的积累&#xff0c;并将理论应用到作品中。了解当下设计的流行趋势&#xff0c;设计注重细节、重视用户体验&#xff0c;对色彩搭配有着浓厚的兴趣&…

13、深度学习之神经网络

深度学习是机器学习中重要的一个学科分支,它的特点就在于需要构建多层“深度”的神经网络。 人们在探索人工智能初期,就曾设想构建一个用数学方式来表达的模型,它可以模拟人的大脑,大脑我们都知道,有很多神经元,每个神经元之间通过突触链接。 神经网络的设计就是模仿了这…

11.6AOP

一.AOP是什么 是面向切面编程,是对某一类事情的集中处理. 二.解决的问题 三.AOP的组成 四.实现步骤 1.添加依赖(版本要对应): maven仓库链接 2.添加两个注解 3.定义切点 4.通知 5.环绕通知 五.excution表达式 六.AOP原理 1.建立在动态代理的基础上,对方法级别的拦截. 2. …

【机器学习】贝叶斯分类器

贝叶斯分类器是一种概率模型&#xff0c;利用贝叶斯公式来解决分类问题。假设样本的特征向量服从一定的概率分布&#xff0c;我们就可以计算出该特征向量属于各个类的条件概率。分类结果是条件概率最大的分类结果。如果假设特征向量的每个分量彼此独立&#xff0c;则它是朴素贝…

【OpenCV实现图像:OpenCV利用Python创作热力图】

文章目录 概要读取图像图像灰度化**像素化效果**小结 概要 热力图是一种强大的统计图表&#xff0c;通过对数据进行色彩映射&#xff0c;直观展示了数据分布的热度和密度。在绘制热力图时&#xff0c;关键在于指定颜色映射的规则&#xff0c;这决定了图中不同数值的呈现方式。…

渗透实例------2个星期艰难的渗透纪实

2个星期艰难的渗透纪实 kyo327 入侵原因,需删一帖子,目标用www.111.com代替,前期通过初期的网站文件暴力猜解,扫描到robots.txt这个文件,有以下目录。如图1: 图1 再通过对这些文件的访问,从3gadm.php文件的标题栏得到该网站采用的是diy-page8.3的cms,自然可以先用搜索…

Android JNI 异常定位(2)—— addr2line

Android native报错有时候只有一句 signal 11 (SIGSEGV)&#xff0c;这种情况仅通过log是很难定位到问题的。不过Android 在/data/tombstones目录保存了错误的堆栈信息&#xff0c;为定位bug提供了路径。不过一般这里的log都无法像java一样直接定位的出错的行数。如下图&#x…

2023做车载测试真的可以远离内耗!转行车载月入20K!

2023年&#xff0c;车载测试正处于一个发展阶段&#xff0c;随着新能源汽车的蓬勃发展&#xff0c;电气化、智能化逐渐成为发展趋势。在汽车开发过程中&#xff0c;测试是非常重要的一个环节。现在软件越来越多地被应用到汽车上&#xff0c;对软件测试的需求也越来越多、越来越…

数据库数据恢复—MongoDB数据库文件拷贝出现错误的数据恢复案例

MongoDB数据库数据恢复环境&#xff1a; 一台Windows Server操作系统的虚拟机&#xff0c;虚拟机上部署有MongoDB数据库。 MongoDB数据库故障&检测&#xff1a; 在未关闭MongoDB服务的情况下&#xff0c;工作人员将MongoDB数据库文件拷贝到其他分区&#xff0c;然后将原数…