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

2023-11-22 08:12

本文主要是介绍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;}
}

这篇关于Java使用x-www-form-urlencoded发请求的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/408743

相关文章

Java NoClassDefFoundError运行时错误分析解决

《JavaNoClassDefFoundError运行时错误分析解决》在Java开发中,NoClassDefFoundError是一种常见的运行时错误,它通常表明Java虚拟机在尝试加载一个类时未能... 目录前言一、问题分析二、报错原因三、解决思路检查类路径配置检查依赖库检查类文件调试类加载器问题四、常见

Java注解之超越Javadoc的元数据利器详解

《Java注解之超越Javadoc的元数据利器详解》本文将深入探讨Java注解的定义、类型、内置注解、自定义注解、保留策略、实际应用场景及最佳实践,无论是初学者还是资深开发者,都能通过本文了解如何利用... 目录什么是注解?注解的类型内置注编程解自定义注解注解的保留策略实际用例最佳实践总结在 Java 编程

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

windows和Linux使用命令行计算文件的MD5值

《windows和Linux使用命令行计算文件的MD5值》在Windows和Linux系统中,您可以使用命令行(终端或命令提示符)来计算文件的MD5值,文章介绍了在Windows和Linux/macO... 目录在Windows上:在linux或MACOS上:总结在Windows上:可以使用certuti

CentOS和Ubuntu系统使用shell脚本创建用户和设置密码

《CentOS和Ubuntu系统使用shell脚本创建用户和设置密码》在Linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设置密码,本文写了一个shell... 在linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设

Python使用Matplotlib绘制3D曲面图详解

《Python使用Matplotlib绘制3D曲面图详解》:本文主要介绍Python使用Matplotlib绘制3D曲面图,在Python中,使用Matplotlib库绘制3D曲面图可以通过mpl... 目录准备工作绘制简单的 3D 曲面图绘制 3D 曲面图添加线框和透明度控制图形视角Matplotlib

Pandas中统计汇总可视化函数plot()的使用

《Pandas中统计汇总可视化函数plot()的使用》Pandas提供了许多强大的数据处理和分析功能,其中plot()函数就是其可视化功能的一个重要组成部分,本文主要介绍了Pandas中统计汇总可视化... 目录一、plot()函数简介二、plot()函数的基本用法三、plot()函数的参数详解四、使用pl

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Java 实用工具类Spring 的 AnnotationUtils详解

《Java实用工具类Spring的AnnotationUtils详解》Spring框架提供了一个强大的注解工具类org.springframework.core.annotation.Annot... 目录前言一、AnnotationUtils 的常用方法二、常见应用场景三、与 JDK 原生注解 API 的

Java controller接口出入参时间序列化转换操作方法(两种)

《Javacontroller接口出入参时间序列化转换操作方法(两种)》:本文主要介绍Javacontroller接口出入参时间序列化转换操作方法,本文给大家列举两种简单方法,感兴趣的朋友一起看... 目录方式一、使用注解方式二、统一配置场景:在controller编写的接口,在前后端交互过程中一般都会涉及