httpclient 聚合

2023-11-20


依赖

<dependency>
     <groupId>org.apache.httpcomponents</groupId>
     <artifactId>httpclient</artifactId>
     <version>4.5.3</version>
 </dependency>

 <dependency>
     <groupId>org.apache.httpcomponents</groupId>
     <artifactId>httpmime</artifactId>
     <version>4.5.3</version>
 </dependency>

DefaultHttpClient 废弃

  • DefaultHttpClient httpclient = new DefaultHttpClient ();
  • 使用 CloseableHttpClient client = HttpClients.createDefault(); 替换

设置代理

HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
        httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36");
        HttpHost proxy = new HttpHost("127.0.0.1",8008);
        RequestConfig requestConfig = RequestConfig.custom()
                .setProxy(proxy)
                .setConnectTimeout(10000)
                .setSocketTimeout(10000)
                .setConnectionRequestTimeout(3000)
                .build();
        httpPost.setConfig(requestConfig);

传文件

  • 转载于:http://hc.apache.org/httpcomponents-client-4.5.x/httpmime/examples/org/apache/http/examples/entity/mime/ClientMultipartFormPost.java
import java.io.File;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * Example how to use multipart/form encoded POST request.
 */
public class ClientMultipartFormPost {

    public static void main(String[] args) throws Exception {
        if (args.length != 1)  {
            System.out.println("File path not given");
            System.exit(1);
        }
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost("http://localhost:8080" +
                    "/servlets-examples/servlet/RequestInfoExample");

            FileBody bin = new FileBody(new File(args[0]));
            StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .addPart("bin", bin)
                    .addPart("comment", comment)
                    .build();


            httppost.setEntity(reqEntity);

            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

}

HttpClientUtil (version=4.3.6 )

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.3.6</version>
</dependency>
import org.apache.http.HttpEntity;
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.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;

public class HttpClientUtil {


    public static String doPost(String url, String jsonStr){
        StringEntity stringEntity = new StringEntity(jsonStr, ContentType.APPLICATION_JSON);
        return doPost(url, stringEntity);
    }

    public static String doPost(String url, HttpEntity entity){
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
        //httpPost.addHeader("Accept", " application/json");
//        List<NameValuePair> list = new ArrayList<NameValuePair>();
//        list.add(new BasicNameValuePair("accountSecret",accountSecret));
//        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");
        httpPost.setEntity(entity);
        // 发起请求
        CloseableHttpResponse response = null;
        String result = null;
        try {
            response = client.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();

            result = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(response != null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    public static String doGet(String url){
        CloseableHttpClient client = HttpClients.createDefault();
       // HttpClient httpClient = new HttpClient();
        if(url ==null){
        	return null;
        }
        HttpGet getMethod = new HttpGet(url);
        // 发起请求
        CloseableHttpResponse response = null;
        String result = null;
        try {
            response = client.execute(getMethod);
            int statusCode = response.getStatusLine().getStatusCode();

            HttpEntity entity = response.getEntity();
            if(entity !=null){
            	InputStream in = entity.getContent();
            	StringWriter sw = new StringWriter();
                SAXReader xmlReader = new SAXReader();
                Document doc= xmlReader.read(new InputStreamReader(in,"UTF-8"));
                XMLWriter writer_sw = new XMLWriter(sw);
                writer_sw.write(doc);
                result = sw.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(response != null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

httpclient 聚合 的相关文章

  • 程序的调试技巧。

    什么是调试 调试又叫Debug 又称除错 是发现和减少计算机程序或电子仪器设备中程序错误的一个过程 生活中所有发生的事情都一定有迹可循 如果问心无愧 就不需要掩盖也就没有迹象了 如果问心有愧疚 必然需要掩盖 那就一定会有迹象 迹象越多就容易

随机推荐

  • 如何控制asp.net控件TextBox输入内容的长度--(多种方法)

    2009 10 22 17 36 件代码如下
  • 在 CentOS 上安装 Docker Engine

    文章目录 在 CentOS 上安装 Docker Engine 先决条件 操作系统要求 卸载旧版本 安装方法 使用 rpm 存储库安装 设置存储库 安装 Docker Engine 安装最新版本 安装指定版本 以非 root 用户身份管理
  • js获取时间戳的四种方法

  • vscode使用手册

    VS Code Visual Studio Code 是一款轻量级 跨平台的源代码编辑器 支持语法高亮 自动补全 调试 Git 版本控制等功能 下面是一些使用 VS Code 的基本操作 安装和启动 在官网上下载并安装 VS Code 打开
  • react里面的接口调用方法

    react接口调用 我们通过npm create react app my app创建react项目 在项目里都是要进行接口调用来获取数据 进行增删改查各种操作的 所以掌握接口调用方式是非常必要的 话不多说进入正题 想要掌握接口调用的内里逻
  • 何恺明组《Designing Network Design Spaces》的整体解读(一篇更比六篇强)

    本文原载自知乎 已获原作者授权转载 请勿二次转载 https zhuanlan zhihu com p 122557226 statistics 大法好 DL不是statistics 因为DL不如statistics 基本全文从统计学的角度
  • 编程猫python讲师面试_【编程猫教师面试】笔试:试题+打字测速-看准网

    985师范本加硕 想要从事k12教育 坚挺到最后一轮但是未通过的小姐姐掩面飘过 来谈谈我的面试感受吧 个人觉得猫厂管培生的面试整体流程安排挺合理的 有感觉确实是在用心的挑选人才 然后所有的面试官都很nice 我是直接在boss直聘上投的简历
  • ffmpeg最简单的解码保存YUV数据

    文章转载自 http blog chinaunix net xmlrpc php r blog article id 4584541 uid 24922718 video的raw data一般都是YUV420p的格式 简单的记录下这个格式的
  • 技术英雄会【新闻】CSDN最有价值博客TOP10颁奖【图】【我在左边数第四个】

    2007年04月06日 10 04 新浪科技夹带些私货 呵呵 社区英雄会 一 问周鸿祎一个问题 社区英雄会 二 问CSDN一个信息过滤器的问题 技术英雄会 三 社区英雄们的与会感言大赏 技术英雄会 四 也谈如何发掘到需要的内容和英雄 图为
  • linux_compress

    tar 解包 tar xvf FileName tar 打包 tar cvf FileName tar DirName 注 tar是打包 不是压缩 gz 解压1 gunzip FileName gz 解压2 gzip d FileName
  • 调试器GDB的基本使用方式(一)

    GDB的功能及其丰富 我们按照调试的流程进行说明 基本用法很简单 流程如下所示 带着调试选项编译 构建调试对象 启动调试器 GDB 设置断点 显示栈帧 显示值 继续执行 一 准备 通过 gcc 的 g 选项生成调试信息 gcc Wall O
  • Qt bool转QString再转回bool方法

    可能在传递参数的过程中 传的一是个bool值 而后面 在参数的转换传递过程中 只能传一个QString 最后又需要得到一个bool值 这时就可以使用这种方法 bool testParam QString tempParam QString
  • matlab傅里叶变换漫谈

    Introduction 由于research需要 不得已开始回顾关于高数的基本知识 写在这里方便记录 这个故事告诉我们 What goes around comes around meaning that life has a funny
  • java二维数组随机赋值_java 二维数组随机赋值

    java 二维数组随机赋值 2021 01 31 00 08 55 简介 目的 使用二维数组打印一个 10 行杨辉三角 视频教程推荐 java课程 思路 1 第一行有 1 个元素 第 n 行有 n 个元素 2 每一行的第一个元素和最后一个元
  • HTML头部

    目录 实例 HTML 元素 HTML
  • Linux命令·rm

    linux中删除文件和目录的命令 rm命令 rm是常用的命令 该命令的功能为删除一个目录中的一个或多个文件或目录 它也可以将某个目录及其下的所有文件及子目录均删除 对于链接文件 只是删除了链接 原有文件均保持不变 rm是一个危险的命令 使用
  • angular2 Http请求

    提供HTTP服务 HttpModule并不是Angular的核心模块 它是Angular用来进行Web访问的一种可选方式 并位于一个名叫 angular http的独立附属模块中 编辑app module ts import HttpMod
  • Fortran基础1——声明及数据类型

    声明及数据类型 一 声明的意义 告诉编译器要预留一些存放数据的内存空间 二 基本数据类型 数据类型 描述 整数 integer a 浮点数 real a 字符 character a 逻辑变量 logical a 复数 complex a
  • 程序员的自我修养——链接、装载与库

    1 温故而知新 操作系统概念 北桥 连接高速芯片 系统调用接口 以软件中断的方式提供 如Linux使用0x80号中断作为系统调用接口 多任务系统 进程隔离 设备驱动 直接使用物理内存的弊端 地址空间不隔离 内存使用效率低 程序运行的地址不确
  • httpclient 聚合

    文章目录 依赖 DefaultHttpClient 废弃 设置代理 传文件 HttpClientUtil version 4 3 6 依赖