HttpEntity的类型及其使用(各种继承的使用)「建议收藏」

HttpEntity的类型及其使用(各种继承的使用)packagecom.lyj.demo.customTests;importorg.apache.http.Header;importorg.apache.http.HeaderElement;importorg.apache.http.HttpEntity;importorg.apache.http.HttpResponse;importorg.apache.http.ParseException;importorg.apa

大家好,又见面了,我是你们的朋友全栈君。

HttpEntity的类型及其使用(各种继承的使用)

package com.lyj.demo.customTests;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentProducer;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.EntityTemplate;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Map;

import static java.nio.charset.StandardCharsets.UTF_8;

/** * @author 凌兮 * @date 2020/10/8 13:45 * HttpEntity相关类测试 */
@RunWith(SpringJUnit4ClassRunner.class)
public class HttpEntityTest { 
   

    /** * basicHttpEntity测试 * 代表底层流的基本实体。通常是在http报文中获取的实体。 * 他只有一个空参的构造方法。刚创建时没有内容,长度为负值。 * 需要通过两个方法,把值赋进去 */
    @Test
    public void basicHttpEntityTest() throws IOException { 
   
        InputStream inputStream = null;
        // BasicHttpEntity这类就是一个输入流的内容包装类,包装内容的相关的编码格式,长度等
        BasicHttpEntity basicHttpEntity = new BasicHttpEntity();
        // 设置内容
        basicHttpEntity.setContent(inputStream);
        // 设置长度
        basicHttpEntity.setContentLength(inputStream.available());
        // 暂时不明白他是干啥的
        basicHttpEntity.setChunked(false);
    }

    /** * byteArrayEntity测试 * 是自我包含的,可重复获得使用的, * 从指定的字节数组中取出内容的实体。 * 字节数组是这个实体的构造方法的参数。 */
    @Test
    public void byteArrayEntityTest() { 
   
        ByteArrayEntity byteArrayEntity = new ByteArrayEntity("你好呀".getBytes());
        // 返回byteArrayInputStream对象
        ByteArrayInputStream content = (ByteArrayInputStream) byteArrayEntity.getContent();
         /*public InputStream getContent() { return new ByteArrayInputStream(this.b, this.off, this.len); }*/
    }

    /** * StringEntity测试 * 是自我包含的可重复的实体。通过String创建的实体。 * 有两个构造方法,一个是自Sring为参数的构造方法, * 一个是以String和字符编码为参数的构造方法 */
    @Test
    public void stringEntityTest() throws UnsupportedEncodingException { 
   
        StringBuilder stringBuilder = new StringBuilder();
        // 获取系统信息集合,这个集合是不可以修改的
        Map<String, String> getenv = System.getenv();
        for (Map.Entry<String,String> entry : getenv.entrySet()) { 
   
            stringBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("\n");
        }
        // 拼接后的系统信息集合
        String content = stringBuilder.toString();
        System.out.println(content);
        // 创建只带字符串参数的entity
        StringEntity entity = new StringEntity(content);
        // 创建带字符串参数的和指定的字符编码格式的entity
        StringEntity entity1 = new StringEntity(content, UTF_8);

    }

    /** * InputStream测试 * 是流式不可以重复的实体。 * 构造方法是InputStream 和内容长度,内容长度是输入流的长度。 */
    @Test
    public void inputStreamEntityTest() throws IOException { 
   
        InputStream inputStream = null;
        // InputStreamEntity严格是对内容和长度相匹配的。用法和BasicHttpEntity类似
        InputStreamEntity inputStreamEntity = new InputStreamEntity(inputStream, inputStream.available());
    }

    /** * fileEntity测试 * 自我包含式,可以重复的实体。参数传入文件和文件类型。 */
    @Test
    public void fileEntityTest() { 
   
        FileEntity fileEntity = new FileEntity(new File(""), ContentType.APPLICATION_FORM_URLENCODED);

        FileEntity fileEntity1 = new FileEntity(new File(""), ContentType.APPLICATION_JSON);
        // 已经过时了
// FileEntity fileEntity1 = new FileEntity(new File(""), ContentType.APPLICATION_JSON.getMimeType());
        System.out.println(ContentType.APPLICATION_JSON.getMimeType());
    }

    /** * EntityTemplete测试 * 从ContentProducer接口接受内容的实体。 * 在ContentProducer的实现类中写入想要写入的内容 */
    @Test
    public void entityTempleteTest() throws IOException { 
   
        ContentProducer contentProducer = new ContentProducer() { 
   
            @Override
            public void writeTo(OutputStream outputStream) throws IOException { 
   
                outputStream.write("你好呀".getBytes());
            }
        };
        EntityTemplate entityTemplate = new EntityTemplate(contentProducer);
        entityTemplate.writeTo(System.out);
// System.out.println(entityTemplate.getContent());

    }

    /** * HttpEntityWrapper测试 * 这个是创建被包装实体的基类,有被包装实体的引用。 * 相当于实体的代理类,被包装实体是他的一个属性。 */
    @Test
    public void httpEntityWrapperTest() throws IOException { 
   
        HttpEntityWrapper httpEntityWrapper = new HttpEntityWrapper(new HttpEntity() { 
   
            @Override
            public boolean isRepeatable() { 
   
                return false;
            }

            @Override
            public boolean isChunked() { 
   
                return false;
            }

            @Override
            public long getContentLength() { 
   
                return 0;
            }

            @Override
            public Header getContentType() { 
   
                return null;
            }

            @Override
            public Header getContentEncoding() { 
   
                return null;
            }

            @Override
            public InputStream getContent() throws IOException, UnsupportedOperationException { 
   
                return null;
            }

            @Override
            public void writeTo(OutputStream outputStream) throws IOException { 
   
                outputStream.write("你好呀".getBytes());
            }

            @Override
            public boolean isStreaming() { 
   
                return false;
            }

            @Override
            public void consumeContent() throws IOException { 
   

            }
        });
        httpEntityWrapper.writeTo(System.out);
        System.out.println(httpEntityWrapper.getContent());
    }

    /** * BufferedHttpEntity测试 * 是HttpEntityWarpper的子类,可以把不可以重复的实体, * 实现成可以重复的实体。它从提供的实体中读取内容,缓存到内容中。 */
    @Test
    public void bufferedHttpEntityTest() throws IOException { 
   
        BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(new HttpEntity() { 
   
            @Override
            public boolean isRepeatable() { 
   
                return false;
            }

            @Override
            public boolean isChunked() { 
   
                return false;
            }

            @Override
            public long getContentLength() { 
   
                return 0;
            }

            @Override
            public Header getContentType() { 
   
                return null;
            }

            @Override
            public Header getContentEncoding() { 
   
                return null;
            }

            @Override
            public InputStream getContent() throws IOException, UnsupportedOperationException { 
   
                return null;
            }

            @Override
            public void writeTo(OutputStream outputStream) throws IOException { 
   
                outputStream.write("你好呀".getBytes());
            }

            @Override
            public boolean isStreaming() { 
   
                return false;
            }

            @Override
            public void consumeContent() throws IOException { 
   

            }
        });
        bufferedHttpEntity.writeTo(System.out);
        System.out.println(bufferedHttpEntity.getContent());
        // 入参校验函数
// Args.notNull();
    }

    /** * HttpEntity测试1 * HttpEntity实体即可以使流也可以使字符串形式。具体有什么用法看他的方法解释 */
    @Test
    public void httpEntityTest1() throws IOException { 
   
// new StringEntity();
        try { 
   
            HttpEntity entity = new StringEntity("这是一个字符串", StandardCharsets.UTF_8);
            // 内容类型
            System.out.println(entity.getContentType());
            // 内容的编码格式
            System.out.println(entity.getContentEncoding());
            // 内容的长度
            System.out.println(entity.getContentLength());
            // 内容的长度
            System.out.println(entity.getContent().available());
            // 获取流
            System.out.println(entity.getContent());
            // 把内容转换成字符串
            System.out.println(EntityUtils.toString(entity));
            // 把内容转为字节数组并获取长度
            System.out.println(EntityUtils.toByteArray(entity).length);
            System.out.println("----------------------------------");
            // 获取entity内容类型
            Header header = entity.getContentType();
            System.out.println(header);
            // 内容类型元素
            HeaderElement[] elements = header.getElements();
            System.out.println(elements);
            // 通过entity获取内容类型
            ContentType contentType = ContentType.get(entity);
            System.out.println(contentType);
        } catch (IOException | UnsupportedOperationException | UnsupportedCharsetException | ParseException e) { 
   
            throw new RuntimeException(e);
        }
    }

    /** * HttpEntity测试2 * 对于实体的资源使用完之后要适当的回收资源,特别是对于流实体。 */
    @Test
    public void httpEntityTest2() throws IOException { 
   
        HttpResponse response = null;
        HttpEntity entity = response.getEntity();

        if (entity != null) { 
   
            InputStream inputStream = entity.getContent();
            try { 
   
                // 做一些流式操作
            } catch (Exception e) { 
   
                // 异常捕捉
                e.printStackTrace();
            } finally { 
   
                // 由于InputSteam实现了Closeable接口,可以实现自动关闭流,所以这里可以不用关闭流,
                if (inputStream != null) { 
   
                    inputStream.close();
                }
                // 采用这种方法也可以实现关闭流
                EntityUtils.consume(entity);
            }
        }

    }
}

参考链接

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/126070.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 硅谷科技公司ceo_硅谷 码农转行

    硅谷科技公司ceo_硅谷 码农转行一位普通的华人程序员,是如何在美国赤手拼搏二十载,成为全美最佳雇主,为三分之一的世界500强企业提供视频会议服务。

    2022年10月11日
    4
  • docker部署jenkins安装使用教程_docker安装python

    docker部署jenkins安装使用教程_docker安装python前言使用docker安装jenkins环境,jenkins构建的workspace目录默认是在容器里面构建的,如果我们想执行python3的代码,需进容器内部安装python3的环境。进jenki

    2022年7月30日
    4
  • 传真服务器的定义与选购

    传真服务器的定义与选购 AOFAX热点:传真服务器的定义与选购服务信息卡:联系人:朱成军服务热线:15920885998 商务QQ:909075483.一、传真服务器和传真系统传真服务器定义:所谓传真服务器,就是为企业内部所有员工提供电脑传真收发服务的设备,能够长期脱离其他电脑独立工作,是传真服务器的必要条件。传真服务器由传真软件、传真卡、工控机等组成。传真系统:传真服务器在某些场合也

    2022年6月28日
    25
  • Python 获取时间戳_python精确到毫秒时间戳

    Python 获取时间戳_python精确到毫秒时间戳python获取当前时间戳的方法:1、使用time模块,语法为“time.time()”;2、使用datetime模块,语法为“datetime.datetime.now().timestamp()”。使用模块timeimporttimenow=time.time()print(now)1593580247.232345使用模块datetime模块datetime提供了以更面向对象的方式操作…

    2022年10月2日
    3
  • python编程考试有哪些(python编程考试模拟题)

    python编程考试有哪些(python编程考试模拟题)2021国内外主流机器人编程赛事+等级考试Scratch编程、C++编程、Python编程等多个赛项,评比类、竞技类不同比赛形式自主选择。多个国内外主流机器人编程赛事,总能帮助孩子找到施展能力、表现创意的舞台。机器人、编程、人工智能等级考试篇全国青少年机器人技术等级考试和全国青少年软件编程等级考试均由中国电子…。2021机器人编程赛事+等级考试攻略之国内外主流赛事及能力测评篇上周,玛酷在公众号发布了一篇名为《2021机器人编程赛事+等级考试攻略之教育部白名单赛事篇》的文章。文章中为大家介绍了20

    2022年5月17日
    65
  • 数据库事务4种隔离级别及7种传播行为「建议收藏」

    数据库事务4种隔离级别及7种传播行为「建议收藏」数据库事务4种隔离级别及7种传播行为

    2022年4月23日
    41

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号