做网站的实习日记/淘数据
作为Java开发程序员,需要我们经常写一些工具类来简化开发过程,我们自己肯定写过或者用过HttpUtils用来发送http请求,但是每次手写太繁琐了,于是就按照标准写了一个Http工具类,现在分享出来。
1.HTTP请求简介
HTTP(Hypertest Transfer Protocol)是用于传输像HTML这样的超文本文件的应用层协议。它被设计用于WEB浏览器端和WEB服务端的交互,但也有其它用途。HTTP遵循经典的client-server模型,客户端发起请求尝试建立连接,然后等待服务端的应答。HTTP是无状态协议,这意味着服务端在两次请求间不会记录任何状态。
2.Http请求四要素
一个HTTP请求报文由四个部分组成:请求行、请求头部、空行、请求数据。
1、请求行
请求行由请求方法字段、URL字段和HTTP协议版本字段3个字段组成,它们用空格分隔。
2、请求头部
HTTP客户程序(例如浏览器),向服务器发送请求的时候必须指明请求类型(一般是GET或者POST)。如有必要,客户程序还可以选择发送其他的请求头。大多数请求头并不是必需的,但Content-Length除外。对于POST请求来说Content-Length必须出现。
3、空行
它的作用是通过一个空行,告诉服务器请求头部到此为止。
4、请求数据
若方法字段是GET,则此项为空,没有数据。若方法字段是POST,则通常来说此处放置的就是要提交的数据。
HttpUtils的代码
package com.zuoan.utils;import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;public class HttpUtil {private static final CloseableHttpClient httpclient = HttpClients.createDefault();private static final String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36";/*** 发送HttpGet请求*/public static String sendGet(String url, String token) {String result = null;CloseableHttpResponse response = null;try {URIBuilder uriBuilder = new URIBuilder(url);HttpGet httpGet = new HttpGet(url);httpGet.setHeader("User-Agent", userAgent);httpGet.setHeader("Authorization", "token " + token);response = httpclient.execute(httpGet);HttpEntity entity = response.getEntity();if (entity != null) {result = EntityUtils.toString(entity);}} catch (Exception e) {log.error("处理失败 {}" + e);e.printStackTrace();} finally {if (response != null) {try {response.close();} catch (IOException e) {log.error(e.getMessage());}}}return result;}/*** 发送HttpGet请求,参数为map格式*/public static String sendGet(String url, Map<String, String> map) {String result = null;CloseableHttpResponse response = null;try {URIBuilder uriBuilder = new URIBuilder(url);for (Map.Entry<String, String> entry : map.entrySet()) {uriBuilder.setParameter(entry.getKey(), entry.getValue());}HttpGet httpGet = new HttpGet(uriBuilder.build());httpGet.setHeader("User-Agent", userAgent);response = httpclient.execute(httpGet);HttpEntity entity = response.getEntity();if (entity != null) {result = EntityUtils.toString(entity);}} catch (Exception e) {log.error("处理失败 {}" + e);e.printStackTrace();} finally {if (response != null) {try {response.close();} catch (IOException e) {log.error(e.getMessage());}}}return result;}/*** 发送HttpPost请求,参数为map*/public static String sendPost(String url, Map<String, String> map) {// 设置参数List<NameValuePair> formparams = new ArrayList<NameValuePair>();for (Map.Entry<String, String> entry : map.entrySet()) {formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));}// 编码UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);// 设置content-typeformEntity.setContentType("application/json");// 取得HttpPost对象HttpPost httpPost = new HttpPost(url);// 防止被当成攻击添加的httpPost.setHeader("User-Agent", userAgent);// 接收参数设置httpPost.setHeader("Accept", "application/json");// 参数放入EntityhttpPost.setEntity(formEntity);CloseableHttpResponse response = null;String result = null;try {// 执行post请求response = httpclient.execute(httpPost);// 得到entityHttpEntity entity = response.getEntity();// 得到字符串result = EntityUtils.toString(entity);} catch (IOException e) {log.error(e.getMessage());} finally {if (response != null) {try {response.close();} catch (IOException e) {log.error(e.getMessage());}}}return result;}/*** 发送HttpPost请求,参数为json字符串*/public static String sendPost(String url, String jsonStr) {String result = null;// 字符串编码StringEntity entity = new StringEntity(jsonStr, Consts.UTF_8);// 设置content-typeentity.setContentType("application/json");HttpPost httpPost = new HttpPost(url);// 防止被当成攻击添加的httpPost.setHeader("User-Agent", userAgent);// 接收参数设置httpPost.setHeader("Accept", "application/json");httpPost.setEntity(entity);CloseableHttpResponse response = null;try {response = httpclient.execute(httpPost);HttpEntity httpEntity = response.getEntity();result = EntityUtils.toString(httpEntity);} catch (IOException e) {log.error(e.getMessage());} finally {// 关闭CloseableHttpResponseif (response != null) {try {response.close();} catch (IOException e) {log.error(e.getMessage());}}}return result;}/*** 发送不带参数的HttpPost请求*/public static String sendPost(String url) {String result = null;// 得到一个HttpPost对象HttpPost httpPost = new HttpPost(url);// 防止被当成攻击添加的httpPost.setHeader("User-Agent", userAgent);CloseableHttpResponse response = null;try {// 执行HttpPost请求,并得到一个CloseableHttpResponseresponse = httpclient.execute(httpPost);// 从CloseableHttpResponse中拿到HttpEntityHttpEntity entity = response.getEntity();// 将HttpEntity转换为字符串result = EntityUtils.toString(entity);} catch (IOException e) {log.error(e.getMessage());} finally {// 关闭CloseableHttpResponseif (response != null) {try {response.close();} catch (IOException e) {log.error(e.getMessage());}}}return result;}
}
若觉得文章对您有用,不妨 关注 + 收藏 哦!!更多实用文章在首页!
相关文章:

HttpUtils工具类
作为Java开发程序员,需要我们经常写一些工具类来简化开发过程,我们自己肯定写过或者用过HttpUtils用来发送http请求,但是每次手写太繁琐了,于是就按照标准写了一个Http工具类,现在分享出来。 1.HTTP请求简介 HTTP(Hy…...

AI:59-基于深度学习的行人重识别
🚀 本文选自专栏:AI领域专栏 从基础到实践,深入了解算法、案例和最新趋势。无论你是初学者还是经验丰富的数据科学家,通过案例和项目实践,掌握核心概念和实用技能。每篇案例都包含代码实例,详细讲解供大家学习。 📌📌📌在这个漫长的过程,中途遇到了不少问题,但是…...

TCP编程及基础知识
一、端口号 为了区分一台主机接收到的数据包应该转交给哪个进程来进行处理,使用端口号来区分TCP端口号与UDP端口号独立端口用两个字节来表示 2byte(65535个) 众所周知端口:1~1023(1~255之间为众所周知端口ÿ…...

二百零一、Flink——Flink配置状态后端运行后报错:Can not create a Path from an empty string
一、目的 在尚硅谷学习用Flink配置状态后端的项目中,运行报错Exception in thread "main" java.lang.IllegalArgumentException: Can not create a Path from an empty string 二、Flink的状态后端(state backend)类型 (一)Memo…...

Python 爬虫基础
Python 爬虫基础 1.1 理论 在浏览器通过网页拼接【/robots.txt】来了解可爬取的网页路径范围 例如访问: https://www.csdn.net/robots.txt User-agent: * Disallow: /scripts Disallow: /public Disallow: /css/ Disallow: /images/ Disallow: /content/ Disallo…...

亚马逊云科技大语言模型的创新科技
陈老老老板🤴 🧙♂️本文专栏:生活(主要讲一下自己生活相关的内容)生活就像海洋,只有意志坚强的人,才能到达彼岸。 🧙♂️本文简述:亚马逊云科技大语言模型的创新科技 🧙♂️上…...

Qt 各种数据类型
目录 1. 基础类型 2. log 输出 3. 字符串类型 3.2 QByteArray 构造函数 数据操作 子字符串查找和判断 遍历 查看字节数 类型转换 3.3 QString 4. QVariant 4.1 标准类型 4.2 自定义类型 5. 位置和尺寸 5.1 QPoint 5.2 QLine 5.3 QSize 5.4 QRect 6. 日期和…...

电动车展示预约小程序的作用如何
电动车可以说是现在出行常见的方法,覆盖年龄广几乎是每家必备,也有不小大小品牌和经销商,市场需求较高,但在实际经营中,对经销商来时也面临着一些痛点: 1、品牌传播产品展示难 不同品牌竞争很大ÿ…...

「随笔」浅谈2023年云计算的发展趋势
在2023年,云计算的发展趋势将受到政治、经济、社会和科技四个维度的影响。以下是对这些维度的具体分析: 1.1 政治维度: 全球政策推动: 随着全球各国政策对云计算的重视程度不断提高,云计算服务将获得更广泛的市场准入…...

高性能三防工业平板电脑 防摔防爆电容屏工控平板
HT1000是一款高性能工业三防平板,10.1英寸超清大屏,厚度仅14.9mm,超薄机身,可轻松插入袋中,方便携带,搭载8核2.0GHz高性能CPU,行业领先的Android 11.0,设备性能大幅提升,…...

mac flutter pb解析报错:protoc-gen-dart: program not found or is not executable
在mac对pb文件转dart文件的时候报错:protoc-gen-dart: program not found or is not executable 原因是没有安装protoc-gen-dart或者protoc-gen-dart没有设置到环境变量中 解决办法: 1、安装protoc-gen-dart flutter pub global activate protoc_plu…...

PostgreSQL 连接是否要通过SSL,为什么使用SSL 连接后,业务部门会投诉我?
开头还是介绍一下群,如果感兴趣PolarDB ,MongoDB ,MySQL ,PostgreSQL ,Redis, Oceanbase, Sql Server等有问题,有需求都可以加群群内有各大数据库行业大咖,CTO,可以解决你的问题。加群请联系 liuaustin3 ,(…...

Linux驱动开发——USB设备驱动
目录 一、 USB 协议简介 二、 Linux USB 驱动 三、 USB 设备驱动实例 一、 USB 协议简介 USB(Universal Serial Bus,通用串行总线)正如它的名字一样,是用来连接PC外设的一种通用串行总线,即插即用和易扩展是它最大的特点。所谓即插即用&am…...

微服务使用指南
微服务使用指南 1.初识微服务 微服务可以认为是一种分布式架构的解决方案,提供服务的独立性和完整性,做到服务的高内聚、低耦合。 目前服务架构主要包含:单体架构和分布式架构。 1.1 单体架构 单体架构:把所有业务功能模块都…...

MYSQL运维篇(已完结)
一、日志 1. 错误日志 2. 二进制日志 😎 介绍 😎 日志格式 😎 日志查看 😎 日志删除 3. 查询日志 4. 慢查询日志 二、主从复制 1. 概述 2. 原理 3. 搭建 4. 总结 三、分库分表 1. 介绍 🍤 问题分析 🍤…...

MapReduce性能优化之小文件问题和数据倾斜问题解决方案
文章目录 MapReduce性能优化小文件问题生成SequenceFileMapFile案例 :使用SequenceFile实现小文件的存储和计算 数据倾斜问题实际案例 MapReduce性能优化 针对MapReduce的案例我们并没有讲太多,主要是因为在实际工作中真正需要我们去写MapReduce代码的场…...

面向萌新的数学建模入门指南
时间飞逝,我的大一建模生涯也告一段落。感谢建模路上帮助过我的学长和学姐们,滴水之恩当涌泉相报,写下这篇感想,希望可以给学弟学妹们一丝启发,也就完成我的想法了。拙劣的文笔,也不知道写些啥,…...

基于 golang 从零到一实现时间轮算法 (二)
Go实现单机版时间轮 上一章介绍了时间轮的相关概念,接下来我们会使用 golang 标准库的定时器工具 time ticker 结合环状数组的设计思路,实现一个单机版的单级时间轮。 首先我们先运行一下下面的源码,看一下如何使用。 https://github.com/x…...

【系统架构设计】架构核心知识: 5 系统安全性与保密性设计
目录 一 信息安全基础 1 信息安全的基本要素 2 信息安全的范围 3 网络安全...

无人零售奶柜:革新牛奶购买体验
无人零售奶柜:革新牛奶购买体验 无人零售奶柜的投放地点覆盖了社区、写字楼等靠近居民的场所,大大提升了消费者购买牛奶的体验。这一创新不仅令消费者能够享受到与电商平台相媲美的直供价格优势,还让他们能够购买更多、更丰富的知名品牌牛奶。…...

【Mybatis小白从0到90%精讲】15: Mybatis配置打印SQL日志
文章目录 前言配置日志实现前言 日志(Log)是每个程序都不可或缺的一部分,它可以帮助开发人员诊断和调试问题。Mybatis,作为一款备受赞誉的ORM框架,自然也提供了强大的日志功能。 它不仅提供了内置的标准实现,还支持集成各种主流的日志框架,让我们可以轻松地查看最终执行…...

vue3-video-play视频播放组件
安装: npm i vue3-video-play --save使用说明: https://codelife.cc/vue3-video-play/guide/install.html...

vue项目中页面遇到404报错
vue页面访问正常,但是一刷新就会404的问题解决办法: 1.解决方法: 将vue的路由模式 mode: history 修改为 mode: hash模式 //router.js文件 const router new Router({//mode: history, mode: hash,routes: [{ path: /, redirect: /login …...

快手直播弹幕websocket protobuf序列化与反序列化
系列文章目录 websocket训练地址:https://www.qiulianmao.com,正在搭建中 基础-websocket逆向基础-http拦截基础-websocket拦截基础-base64编码与解码基础-python实现protobuf序列化与反序列化基础-前端js实现protobuf序列化与反序列化基础-protobufjs实现protobuf序列化与反…...

viple入门(三)
(1)条件循环活动 条件循环活动中,必须给定条件,条件成立,则执行条件循环的后续程序。 条件不成立,则不执行后续程序。 从报错信息来看,程序提示:条件循环要和结束循环活动一起使用。…...

Vue渲染函数渲染html
版本 vue2.6 使用 domProps属性 domProps: {innerHTML: xxx},官方文档...

Odoo|“视图”和“模型”之间的数据传输
01前言 今天带领大家学习Odoo系统中“视图”与“模型”之间的数据传输。看题目我们可以知道,这篇文章是面向的是Odoo的初学者。Odoo作为当前最普遍的二开ERP系统,其开源,模块化,灵活开发的属性使得它在ERP相关领域十分受青睐。 …...

Electron进程通信的另一种方式
上一篇讲述了主进程和渲染进程之间的通信,其中是通过调用 ipcMain 和 ipcRenderer 来完成的。比如渲染进程给主进程发送一个消息,然后主进程再返回一个消息给渲染进程: 主进程的逻辑: ipcMain.on(selectDate,(e,date)>{conso…...

二次型的相关理解
...

Spring框架中用于注入构造函数参数的标签constructor-arg
一、constructor-arg的介绍 constructor-arg是Spring框架中用于注入构造函数参数的标签,它可以用于实现依赖注入的方式之一。在实际开发中,我们通常会在Spring配置文件中声明bean的时候使用constructor-arg标签注入构造函数参数。 constructor-arg标签有…...