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

news2024/11/18 11:23:37

平常在开发过程中用的最多的就是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;
    }
}

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

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

相关文章

Monoxide relay机制和连弩挖矿

这篇文章就两个点&#xff0c;relay机制 、 连弩挖矿 relay 最终原子性 Eventual Atomicity 一笔跨链交易&#xff0c;从取款shard中发出&#xff0c;到存款shard中. 当收款shard中将这笔夸片交易打包上链后&#xff0c;原子性才执行结束。 这样做的延迟是比较小的。 如何应…

uniapp、微信小程序返回上页面刷新数据

目录 前言&#xff1a; 方法1&#xff1a; 方法2&#xff1a; 方法3&#xff1a; 前言&#xff1a; 返回上页面刷新数据这个功能主要用于在当前页面点击跳转到另一个页面之后&#xff0c;在另一个页面对数据进行了操作&#xff0c;比如&#xff1a;阅读量&#xff0c;然后返…

接入电商数据平台官方开放平台API接口获取商品实时信息数据,销量,评论,详情页演示

要接入电商数据平台官方开放平台API接口获取商品实时信息数据、销量、评论和详情页演示&#xff0c;需要按照以下步骤进行操作&#xff1a; 找到可用的API接口&#xff1a;首先&#xff0c;需要找到支持查询商品信息的API接口。可以在电商数据平台的官方开放平台上查找相应的AP…

react等效memo的方法

视频教程 前端技术&#xff5c;Dan博客&#xff5c;在你写memo()之前_哔哩哔哩_bilibili 把与ExpensiveTree的无关的dom做成一个组件 第二种情况&#xff0c;color在ExpensiveTree组件的父级dom 创建一个组件&#xff0c;将state的color和input写上&#xff0c;而ExpensiveTr…

【智能优化算法】从蚁群到动物园

目录 引言蚁群优化算法&#xff08;ACO&#xff09;ACO 机理ACO 模型描述ACO 移动策略 粒子群优化算法&#xff08;PSO&#xff09;PSO 机理PSO 模型描述 萤火虫群优化算法&#xff08;GSO&#xff09;GSO 机理GSO 模型描述 群智能优化算法 引言 21世纪&#xff0c;人类社会已经…

梯度引导的分子生成扩散模型- GaUDI 评测

GaUDI模型来自于以色列理工Tomer Weiss的2023年发表在预印本ChemRxiv上的工作 《Guided Diffusion for Inverse Molecular Design》。原文链接&#xff1a;Guided Diffusion for Inverse Molecular Design | Materials Chemistry | ChemRxiv | Cambridge Open Engage GaUDI模型…

问题 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,…

超级实用的程序员接单平台,看完少走几年弯路,强推第一个!

”前途光明我看不见&#xff0c;道路曲折我走不完。“ 兜兜转转&#xff0c;心心念念&#xff0c;念念不忘&#xff0c;必有回响。终于找到了....... 网络上好多人都在推荐程序员线上接单&#xff0c;有人说赚得盆满钵满&#xff0c;有的人被坑得破口大骂&#xff0c;还有的人…

苍穹外卖—解决前端时间属性显示问题

项目场景&#xff1a; 点击员工管理 出现显示时间属性问题 输入员工姓名为zhangsan 现实的时间属性是数组类型 问题描述 提示&#xff1a;这里描述项目中遇到的问题&#xff1a; 例如&#xff1a;数据传输过程中数据不时出现丢失的情况&#xff0c;偶尔会丢失一部分数据 APP …

# 聚类系列(一)——什么是聚类?

目前在做聚类方面的科研工作, 看了很多相关的论文, 也做了一些工作, 于是想出个聚类系列记录一下, 主要包括聚类的概念和相关定义、现有常用聚类算法、聚类相似性度量指标、聚类评价指标、 聚类的应用场景以及共享一些聚类的开源代码 下面正式进入该系列的第一个部分&#xff…

利用SVD对图像进行压缩

利用SVD对图像进行压缩 使用SVD能够对数据进行降维&#xff0c;对图像进行SVD&#xff0c;降维之后然后重构数据&#xff0c;还原后的图像就是压缩后的图像。 SVD SVD进行图像压缩所依据的数学原理就是矩阵的近似表示&#xff1a; A m n ≈ U m k ∑ k k V k n T A_{m\…

Web 自动化神器 TestCafe—页面基本操作篇

前 言 Testcafe是基于node.js的框架&#xff0c;以操作简洁著称&#xff0c;是web自动化的神器 今天主要给大家介绍一下testcafe这个框架和页面元素交互的方法。 一、互动要求 使用 TestCafe 与元素进行交互操作&#xff0c;元素需满足以下条件&#xff1a;☟ 元素在 body 页…

五年程序员兼职接单的肺腑之言

不知不觉我已经参加工作&#xff0c;当一个程序员五年了&#xff0c;从一个职场菜鸟逐渐变成老油条&#xff0c;个中辛酸只有自己知道。这五年做过各种兼职接单&#xff0c;踩过不少坑&#xff0c;今天就把我在程序员接单上的一些心得体会分享给大家&#xff0c;希望能对兼职接…

C语言进阶之冒泡排序

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

C++刷题 -- 二分查找

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

网工内推 | 字节原厂,正式编,网络工程师,最高30K*15薪

01 字节跳动 招聘岗位&#xff1a;网络虚拟化高级研发工程师 职责描述&#xff1a; 1、负责字节跳动虚拟网络产品的研发&#xff0c;包括但不局限于网络VPC、NAT、LB负载均衡等&#xff1b; 2、负责字节跳动网络基础平台的研发&#xff0c;包括但不局限于网络控制面系统、容器…

LeetCode算法心得——爬楼梯(记忆化搜索)

大家好&#xff0c;我是晴天学长&#xff0c;第二个记忆化搜索练习&#xff0c;需要的小伙伴可以关注支持一下哦&#xff01;后续会继续更新的。&#x1f4aa;&#x1f4aa;&#x1f4aa; 1&#xff09;爬楼梯 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 每次你可以爬 1 或…

解决Zotero不显示标签的问题

目录 问题描述 解决办法&#xff1a; 问题描述 Zotero是一款学习助手&#xff0c;可以帮助我们梳理文献&#xff0c;方便我们整理。 最近电脑从windows换到mac&#xff0c;重新安装了Zotero&#xff0c;发现之前的一直设置都没有了。比如设置好的标签信息不显示了。如下图: …

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

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

庖丁解牛:NIO核心概念与机制详解 07 _ 字符集

文章目录 Pre概述编码/解码处理文本的正确方式示例程序Code Pre 庖丁解牛&#xff1a;NIO核心概念与机制详解 01 庖丁解牛&#xff1a;NIO核心概念与机制详解 02 _ 缓冲区的细节实现 庖丁解牛&#xff1a;NIO核心概念与机制详解 03 _ 缓冲区分配、包装和分片 庖丁解牛&…