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实现Excel与HTML互转

《Java实现Excel与HTML互转》Excel是一种电子表格格式,而HTM则是一种用于创建网页的标记语言,虽然两者在用途上存在差异,但有时我们需要将数据从一种格式转换为另一种格式,下面我们就来看看... Excel是一种电子表格格式,广泛用于数据处理和分析,而HTM则是一种用于创建网页的标记语言。虽然两

java图像识别工具类(ImageRecognitionUtils)使用实例详解

《java图像识别工具类(ImageRecognitionUtils)使用实例详解》:本文主要介绍如何在Java中使用OpenCV进行图像识别,包括图像加载、预处理、分类、人脸检测和特征提取等步骤... 目录前言1. 图像识别的背景与作用2. 设计目标3. 项目依赖4. 设计与实现 ImageRecogni

Java中Springboot集成Kafka实现消息发送和接收功能

《Java中Springboot集成Kafka实现消息发送和接收功能》Kafka是一个高吞吐量的分布式发布-订阅消息系统,主要用于处理大规模数据流,它由生产者、消费者、主题、分区和代理等组件构成,Ka... 目录一、Kafka 简介二、Kafka 功能三、POM依赖四、配置文件五、生产者六、消费者一、Kaf

Java访问修饰符public、private、protected及默认访问权限详解

《Java访问修饰符public、private、protected及默认访问权限详解》:本文主要介绍Java访问修饰符public、private、protected及默认访问权限的相关资料,每... 目录前言1. public 访问修饰符特点:示例:适用场景:2. private 访问修饰符特点:示例:

python管理工具之conda安装部署及使用详解

《python管理工具之conda安装部署及使用详解》这篇文章详细介绍了如何安装和使用conda来管理Python环境,它涵盖了从安装部署、镜像源配置到具体的conda使用方法,包括创建、激活、安装包... 目录pytpshheraerUhon管理工具:conda部署+使用一、安装部署1、 下载2、 安装3

Mysql虚拟列的使用场景

《Mysql虚拟列的使用场景》MySQL虚拟列是一种在查询时动态生成的特殊列,它不占用存储空间,可以提高查询效率和数据处理便利性,本文给大家介绍Mysql虚拟列的相关知识,感兴趣的朋友一起看看吧... 目录1. 介绍mysql虚拟列1.1 定义和作用1.2 虚拟列与普通列的区别2. MySQL虚拟列的类型2

详解Java如何向http/https接口发出请求

《详解Java如何向http/https接口发出请求》这篇文章主要为大家详细介绍了Java如何实现向http/https接口发出请求,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 用Java发送web请求所用到的包都在java.net下,在具体使用时可以用如下代码,你可以把它封装成一

使用MongoDB进行数据存储的操作流程

《使用MongoDB进行数据存储的操作流程》在现代应用开发中,数据存储是一个至关重要的部分,随着数据量的增大和复杂性的增加,传统的关系型数据库有时难以应对高并发和大数据量的处理需求,MongoDB作为... 目录什么是MongoDB?MongoDB的优势使用MongoDB进行数据存储1. 安装MongoDB

关于@MapperScan和@ComponentScan的使用问题

《关于@MapperScan和@ComponentScan的使用问题》文章介绍了在使用`@MapperScan`和`@ComponentScan`时可能会遇到的包扫描冲突问题,并提供了解决方法,同时,... 目录@MapperScan和@ComponentScan的使用问题报错如下原因解决办法课外拓展总结@

mysql数据库分区的使用

《mysql数据库分区的使用》MySQL分区技术通过将大表分割成多个较小片段,提高查询性能、管理效率和数据存储效率,本文就来介绍一下mysql数据库分区的使用,感兴趣的可以了解一下... 目录【一】分区的基本概念【1】物理存储与逻辑分割【2】查询性能提升【3】数据管理与维护【4】扩展性与并行处理【二】分区的