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("?");
                else
                    param.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;
    }
}

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

2023年【施工升降机司机(建筑特殊工种)】最新解析及施工升降机司机(建筑特殊工种)考试资料

题库来源&#xff1a;安全生产模拟考试一点通公众号小程序 施工升降机司机(建筑特殊工种)最新解析参考答案及施工升降机司机(建筑特殊工种)考试试题解析是安全生产模拟考试一点通题库老师及施工升降机司机(建筑特殊工种)操作证已考过的学员汇总&#xff0c;相对有效帮助施工升…

SMART PLC累计流量功能块(梯形积分法+浮点数累加精度控制)

S7-200SMART PLC数值积分器相关知识请参考下面文章链接: SMART PLC数值积分器功能块(矩形+梯形积分法完整源代码)-CSDN博客文章浏览阅读153次。PLC的数值积分器算法也可以参考下面文章链接:PLC算法系列之数值积分器(Integrator)-CSDN博客数值积分和微分在工程上的重要意义不…

C语言进阶之冒泡排序

✨ 猪巴戒&#xff1a;个人主页✨ 所属专栏&#xff1a;《C语言进阶》 &#x1f388;跟着猪巴戒&#xff0c;一起学习C语言&#x1f388; 目录 前情回顾 1、回调函数 2、冒泡排序 3、库函数qsort cmp&#xff08;sqort中的比较函数&#xff0c;需要我们自定义&#xff09; …

c++|内联函数

一、概念 以inline修饰的函数叫做内联函数&#xff0c;编译时c编译器会在调用函数的地方展开&#xff0c;而不会建立栈帧&#xff0c;提升了程序运行的效率 例子&#xff1a; #include <iostream> using namespace std;int Add(int left, int right) {return left - ri…

详解硬盘的接口、总线和协议

总线&#xff1a;总线是计算机系统中用于连接各个硬件组件的一种通信方式&#xff0c;它可以实现数据、地址和控制信号的传输。在服务器中&#xff0c;内部总线起着承载数据和控制信号的重要作用。总线在单位时间内能传输数据量称为带宽。分为SATA&#xff0c;SAS&#xff0c;P…

Deep Learning for Monocular Depth Estimation: A Review.基于深度学习的深度估计

传统的深度估计方法通常是使用双目相机&#xff0c;计算两个2D图像的视差&#xff0c;然后通过立体匹配和三角剖分得到深度图。然而&#xff0c;双目深度估计方法至少需要两个固定的摄像机&#xff0c;当场景的纹理较少或者没有纹理的时候&#xff0c;很难从图像中捕捉足够的特…

模电 01

一.半导体基本知识 1.优点&#xff1a;体积小、重量轻、使用寿命长、输入功率小、功率转换效率高。 2.性能介于导体与绝缘体 3.常用半导体材料&#xff1a;硅&#xff08;SI&#xff09; 镉&#xff08;Ge&#xff09;,化合物半导体&#xff1a;砷化镓&#xff08;GaAs&…

centos安装kingbase(人大进仓)数据库

一、kingbase官网 https://www.kingbase.com.cn/rjcxxz/index.htm二、官网获取安装镜像文件和licence 三、安装步骤 1、创建新用户kingbase及其同名分组,以及家目录,并设置密码 useradd -m -U kingbase passwd kingbase2、创建自定义安装路径 su root mkdir -p /opt/Kingba…

Nacos介绍与使用

Nacos介绍与使用 文章目录 Nacos介绍与使用一. 什么是Nacos1 Nacos功能1.1 配置中心1.2 注册中心 2.为什么要使用Nacos 二.Nacos 部署安装1. Nacos 部署方式2. Nacos 安装3. 配置数据源4. 开启控制台授权登录&#xff08;可选&#xff09; 三. Nacos配置中心的使用1. 创建配置信…

暴力求解欲哭无泪之保安问题

身为程序员哪一个瞬间让你最奔溃&#xff1f; > 提醒&#xff1a;在发布作品前&#xff0c;请把不需要的内容删掉。 方向一&#xff1a;身为程序员遇到过的奔溃瞬间 写题目想到第一个方法便是暴力求解,然后少情况 题目如下: 方向二&#xff1a;如何解决遇到的奔溃瞬间 不…

[Docker]八.Docker 容器跨主机通讯

一.跨主机通讯原理 在主机192.168.31.140上的docker0(172.17.0.0/16)中有一个容器mycentos( 172.17.0.2/16), 在主机192.168.31.81上的docker0(172.17.0.0/16)中有一个容器mycentos( 172.17.0.2/16),然后在主机192.168.31.140上ping主机192.168.31.81,发现ping不通要实现两个主…

数字化转型导师坚鹏:数字化时代银行网点厅堂营销5大特点分析

数字化时代银行网点厅堂营销存在以下5大特点&#xff1a; 1、产品多样化&#xff1a;在数字化时代&#xff0c;银行的产品和服务变得更加多样化。除了传统的存款、贷款、理财等金融服务外&#xff0c;还新增了各种创新产品&#xff0c;如网上银行、移动支付、投资咨询、保险、…

C++刷题 -- 二分查找

C刷题 – 二分查找 文章目录 C刷题 -- 二分查找一、原理二、例题1.二分查找2.使用二分查找确定target左右边界3.x的平方根 一、原理 条件&#xff1a;数组为有序数组&#xff0c;数组中无重复元素&#xff0c;因为一旦有重复元素&#xff0c;使用二分查找法返回的元素下标可能…

Hibernate 一级缓存,二级缓存,查询缓存

概念&#xff1a; 1.什么是缓存呢&#xff1f; 缓存&#xff1a;是计算机领域的概念&#xff0c;它介于应用程序和永久性数据存储源之间。 缓存&#xff1a;一般人的理解是在内存中的一块空间&#xff0c;可以将二级缓存配置到硬盘。用白话来说&#xff0c;就是一个存储数据的…

问题 R: 胜利大逃亡(HUST)

#include <deque> #define inf 200000 #include<iostream> #include<queue> using namespace std;// 迷宫坐标 int map[59][59][59] { 0 };// 可访问标记 int visit[51][51][51] { 0 }; // 移动方式 int next1[7][4] { {1,0,0},{-1,0,0}, {0,1,0},{0,-1,…

gitlab安装配置及应用

安装 ##安装依赖 yum install -y curl policycoreutils-python openssh-server perl#上传包 rz gitlab-jh-16.5.2-jh.0.el7.x86_64.rpm 安装 yum install gitlab-jh-16.0.3-jh.0.el7.x86_64.rpm 初始化并启动 # 以下两种方法都可以配置访问地址&#xff0c;第一种需要在yum安…

千字文||无聊又数了一下千字文字数

千字文的字数去除标点符号真的整整一千个不多的不少 该文章无技术含量&#xff0c;仅三字经原文&#xff0c;学技术的同学可以止步了 千字文&#xff08;原文&#xff09; 【作者】周兴嗣 【朝代】南北朝 天地玄黄&#xff0c;宇宙洪荒。 日月盈昃&#xff0c;辰宿列张。 寒来…

【LeetCode】104. 二叉树的最大深度

104. 二叉树的最大深度 难度&#xff1a;简单 题目 给定一个二叉树 root &#xff0c;返回其最大深度。 二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。 示例 1&#xff1a; 输入&#xff1a;root [3,9,20,null,null,15,7] 输出&#xff1a;3示例 …

Spring框架学习 -- 创建与使用

目录 (1) 创建spring 项目 ① 创建maven项目 ②添加spring框架支持 ③ 添加启动项 (2) 创建 Bean对象 (3) 将Bean注入到容器 (4) 获取Bean对象 (5) 注意事项 (6) Spring的创建和使用流程图 创作不易多多支持 (1) 创建spring 项目 首先我们使用的开发工具为idea 专业版…