HttpClient发送GET请求和POST请求

使用Apache HttpClient访问JSP发送GET和POST请求 本示例说明了如何使用Apache HttpClient发送GET和POST请求,以及如何发送表单数据,详见代码及说明。对于ASP.NET的网站请求,可以查看使用Apache HttpClient访问ASP.NET发送GET和POST请求   说明: 1、发送表单POST请求时,需要借助HttpWatch或有这种功能的小工具来查看发给服务器的参数有哪些; 2、对于POST请求的表单数据,需要... 阅读详情

一、描述

日常开发过程中,对接三方接口,我们需要调用外围系统的接口,那此时就需要使用工具类调用别的系统的接口,本文主要提供HttpClient来调用接口。

二、需要的jar包

httpclient-4.5.2、

httpcore-4.4.5

jdk的jre包

lombok 1.6.18(可选)

slf4(可选)

三、源码展示

1.GET请求

 public static String doGet(String url, Map<String, String> param) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 返回结果
        String resultString = "";

        // 执行url之后的响应
        CloseableHttpResponse response = null;

        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);

            // 将参数封装到uri里面
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }

            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);

            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {

                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        }
        catch (Exception e) {
            log.info(e.getMessage());
        }
        finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            }
            catch (IOException e) {
                log.info(e.getMessage());
            }
        }
        return resultString;
    }

2. POST请求

public static String doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        CloseableHttpResponse response = null;

        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);

                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);

            resultString = EntityUtils.toString(response.getEntity(), "utf-8");

        }
        catch (Exception e) {
            log.info(e.getMessage());
        }
        finally {
            try {
                response.close();
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                log.info(e.getMessage());
            }
        }

        return resultString;
    }

3.POST提交JSON类型参数

 /**
     * 以JSON方式发请求
     *
     * @param url
     * @param json
     * @return
     */
    public static String doPostJson(String url, String json, int connectTimeOut, int socketTimeOut) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        CloseableHttpResponse response = null;

        String resultString = "";

        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(connectTimeOut).setSocketTimeout(socketTimeOut).build();
            httpPost.setConfig(requestConfig);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);

            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);

            resultString = EntityUtils.toString(response.getEntity(), "utf-8");

        }
        catch (Exception e) {
            log.info(e.getMessage());
        }
        finally {
            try {
                response.close();
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                log.info(e.getMessage());
            }
        }

        return resultString;
    }

4.全部源码奉上

package com.yang.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class HttpRequest {


    public static String doGet(String url, Map<String, String> param) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 返回结果
        String resultString = "";

        // 执行url之后的响应
        CloseableHttpResponse response = null;

        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);

            // 将参数封装到uri里面
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }

            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);

            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {

                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        }
        catch (Exception e) {
            log.info(e.getMessage());
        }
        finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            }
            catch (IOException e) {
                log.info(e.getMessage());
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        CloseableHttpResponse response = null;

        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);

                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);

            resultString = EntityUtils.toString(response.getEntity(), "utf-8");

        }
        catch (Exception e) {
            log.info(e.getMessage());
        }
        finally {
            try {
                response.close();
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                log.info(e.getMessage());
            }
        }

        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, null);
    }

    /**
     * 以JSON方式发请求
     *
     * @param url
     * @param json
     * @return
     */
    public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        CloseableHttpResponse response = null;

        String resultString = "";

        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);

            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);

            resultString = EntityUtils.toString(response.getEntity(), "utf-8");

        }
        catch (Exception e) {
            log.info(e.getMessage());
        }
        finally {
            try {
                response.close();
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                log.info(e.getMessage());
            }
        }

        return resultString;
    }
    /**
     * 以JSON方式发请求
     *
     * @param url
     * @param json
     * @return
     */
    public static String doPostJson(String url, String json, int connectTimeOut, int socketTimeOut) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        CloseableHttpResponse response = null;

        String resultString = "";

        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(connectTimeOut).setSocketTimeout(socketTimeOut).build();
            httpPost.setConfig(requestConfig);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);

            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);

            resultString = EntityUtils.toString(response.getEntity(), "utf-8");

        }
        catch (Exception e) {
            log.info(e.getMessage());
        }
        finally {
            try {
                response.close();
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                log.info(e.getMessage());
            }
        }

        return resultString;
    }
}

觉得不错的关注下公众号吧

å¾ç

 

Java HttpClient execute 永久阻塞问题 HttpClient是Java访问http服务常用的包,之前使用一直没有出现什么问题,前几天编写一个爬虫程序代码时,程序启动后执行没有问题,按正常逻辑执行,过了一段时间便会阻塞在httpclient.execute()方法处,后使用RequestConfig设置connectionTimeout,socketTimeout 均无效,附上当时出问题的代码 CloseableHttpCli... 阅读详情

相关推荐

HttpClient基本使用

HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。当我们在使用扫描支付、查看地图、获取验证码、查看天气等功能时其实,应用程序本身并未实现这些功能,都是在应用程序里访问提供这些功能的服务,访问这些服务需要发送HTTP请求,并且接收响应数据,可通过HttpClient来实现。

Delu3376451753的博客 1200

HttpClient使用详解

HttpClient:是一个接口 首先需要先创建一个DefaultHttpClient的实例 HttpClient httpClient=new DefaultHttpClient(); 发送GET请求: 先创建一个HttpGet对象,传入目标的网络地址,然后调用HttpClient的execute()方法即可: HttpGet HttpGet=new HttpGet(“http://w

姚佳伟 1万+

httpclient-4.5.3.jar 包含CloseableHttpClient

httpclient-4.5.3.jar 包含CloseableHttpClient 和 NameValuePair

HttpClient详细使用示例

HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用...

JustryDeng 56万+

SystemVerilog新手实战指南:iverilog与VScode的完美组合

本文为SystemVerilog新手提供了一套高效入门方案,详细介绍了如何利用开源编译器iverilog与轻量编辑器VScode搭建学习环境。内容涵盖十分钟快速安装配置、首个工程从编码到查看波形的完整流程,并演示了动态数组和队列等SystemVerilog新特性的使用,旨在帮助初学者避开复杂商业工具,快速掌握数字电路设计与验证的核心技能。

f6g7h8i9j的博客 513

PCA9548实战:从硬件连接到Linux驱动的I2C扩展全解析

本文详细解析了PCA9548 I2C多路复用器从硬件连接到Linux驱动配置的全过程。涵盖硬件引脚连接、电源去耦、地址选择等关键设计要点,以及Linux驱动加载、设备树配置和应用层编程技巧,帮助开发者高效实现I2C总线扩展。

weixin_28726391的博客 406

HttpClient 发送 GET 和 POST 请求深度解析

Apache HttpClient 是一个开源的 HTTP 客户端库,提供了对 HTTP 协议的全面支持。它简化了 HTTP 请求的创建和处理,使得开发者可以方便地与 Web 服务器进行交互。HttpClient 支持 HTTP/1.1 和 HTTP/2 协议,并且提供了丰富的功能,如连接管理、请求重试、认证和代理支持等。

xycxycooo的博客 5743

安卓设备安全相关技术

当前安卓设备使用的加密方案是基于Soc中一块可写入的rom实现,称为熔丝,其结果不可逆。 1、secureboot 2、AVB(Android Verify Boot) 3、dm-verity(device mapper) 4、keymaster 5、crypto 6、rpmb(replay private memory block) 7、TEE(Trust execute environment) 8、SELinux .........

weixin_43797328的博客 4836

HttpClient发送get请求和post请求

新建两个项目:test-demo为接口方法,httpclient-demo测试发送get请求和post请求。 1.Httpclient发送get请求 httpclient-demo中测试方法 httpclient-demo中工具类 test-demo接口方法 2.Httpclient发送post请求 httpclient-demo中测试方法 Httpclient-de...

Jeffrey的博客 5376

DataWorks数据安全治理最佳实践

DataWorks基于数据安全治理的常见思路,针对资产梳理、技术体系建设和运营体系建设,提供了一系列数据安全产品能力,您可通过“基础防护建设、数据安全防护措施及策略增强建设、数据安全持续运营”三个阶段在DataWorks上落地数据安全治理项目。参考本文启动数据安全治理项目前,建议您先了解DataWorks数据安全产品相关能力了解DataWorks数据安全产品能力后,您可参考如下三个阶段在DataWorks上落地数据安全治理项目。

soso1968的博客 1438

把外部系统接到 SAP Build Process Automation 的两条路:前台直连与后台编排的完整范式

想把外部系统接入到你的【销售订单管理】审批流程,最稳妥的路径是:在流程里开一个,在 BTP 配好以为核心的 Destination,让前端经由approuter代理、后台通过 Cloud SDK 直连,任务处理用My Inbox或Task APIs,异步对接用。这套组合拳,既满足安全边界与运维规范,又能让前台与后台两个世界各取所需、自然衔接。SAP。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1660

HttpClient发送Get和Post请求

今天带来一个基于HttpClient发送Get以及Post请求,代码一律经过测试,可以放心直接使用。 1:在pom中加入相关依赖 <!-- httpclient相关 --> <dependency> <groupId>org.apache.httpcomponents</groupId> ...

qq_40053836的博客 383

知识图谱实战应用8-从文本关系抽取到知识图谱关系构建流程贯通

大家好,我是微学AI,今天给大家介绍一下知识图谱实战应用8-从文本关系抽取到知识图谱关系构建流程贯通。我们从文本数据中采集到关键信息,并抽取出其中的关系信息,然后在存入图数据库中,整个过程实现自动化,我这里将举一个文本例子进行抽取。 对于知识图谱的构建是将实体、概念和它们之间的关系都以图表形式呈现出来的一种数据结构。要构建一个知识图谱,需要从不同的数据源中采集到相关信息,并将这些信息整合在一起,最终形成一个全面而且精确的知识图谱。

微学AI的博客 2544

C# HttpClient发送Get和Post请求

C# HttpClient发送Get和Post请求 C#.NET命名空间System.Net.Http下的HttpClient可以发送Post/Get请求调用API,也是写过多次但真要自己写起来还要花时间调试,记个笔记。 Post请求 [HttpPost] public async Task<JsonResult> GetWhiteList(string recruitmentPlanId, string kAccount, int pageSize, int pageIndex) { Re

醉酒的李白、的博客 8877

【异常】解决 Cursor 报错 Unexpected seqno: 2 != 1. Please try again, or contact support if the issue 的排坑指南

在使用 Cursor 辅助编程时,你是否遇到过 AI 突然中断输出,并在右下角弹出一个红色的 Network Error 弹窗?今天我们就来彻底解析并解决这个网络断连问题。

奶爸的编程之路,也就一周冷个三天 2469

北斗导航 | SPP、RTK、RTD、PPP-RTK、PPP算法原理,公式及完整matlab代码

开发参考:SPP适合入门学习GNSS定位原理和最小二乘。RTK是工程高精度定位主流方案,但依赖基站。PPP适合无基站区域的广域高精度应用。PPP-RTK是融合两者优点的新一代技术,但系统复杂度最高。· 代码资源:raPPPid(VieVS PPP)是功能完整的MATLAB开源PPP工具箱,支持多系统PPP-AR。MATLAB GPS Toolbox 提供从SPP到PPP的完整功能实现。· 实际应用:农业自动驾驶、无人机航测通常使用网络RTK;大地测量、地壳形变监测常采用PPP事后处理;

尘世冰封的专栏 822

httpclient发送Get请求和Post请求

httpclient发送get请求和post请求

weixin_42274846的博客 5869

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

HttpClient 发送get和post请求的使用方法

HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的,最新的,功能丰富的支持HTTP协议的客户端变成工具包,并且他支持HTTP协议最新的版本和建议。核心API:HttpClientHttpGetHttpPost。

m0_63216787的博客 2716

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

HttpClient发送请求,get和post两种方式,分别带参数和不带参数

(一)、导入HttpCLient的jar包 &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.httpcomponents&lt;/groupId&gt; &lt;artifactId&gt;httpclient&lt;/artifactId&gt; &lt;version&gt;4.5.

BUAACST 3万+

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

HttpClient发送请求:get和post

第一步:jar包 <dependencies> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</versio...

升级打怪 315

Android笔记---使用HttpClient发送POST和GET请求

在Android上发送 HTTP 请求的方式一般有两种, HttpURLConnection 和 HttpClient,关于HttpURLConnection的使用方法能够參考 HTTP之利用HttpURLConnection訪问网页,这里仅仅介绍HttpClient发送POST与GET请求的使用方法。 HttpClient 是 Apache 提供的 HTTP 网络...

diandingyin9417的博客 320

HttpClient发送POST和GET请求

1、使用HttpClient添加的maven依赖(尽量版本平齐或者比我的高,低的可能会出现找不到类的情况) &lt;dependency&gt; &lt;groupId&gt;org.apache.httpcomponents&lt;/groupId&gt; &lt;artifactId&gt;httpclient&lt;/ar...

南巷清风 219

httpclient发送GET和POST请求方式的具体步骤

HttpClient方式发送GET和POST请求实现和后台服务器的通信: 这里只给出了使用httpclient方式发送request所必须要经历的步骤: 以以下代码为例: 发送GET请求 (1)定义get方式要提交的数据(String name = et_username.getText().toString().trim(); String pwd = et_password.getText()...

shuai_xue_dai的博客 6257

httpclient向浏览器发送get和post请求

get请求代码实现 public static void main(String[] args) { CloseableHttpClient httpClient = null; //请求对象 CloseableHttpResponse response = null; //返回对象 HttpEntity entity = null;...

diying6370的博客 263

使用HttpClient发送GET请求和带有表单参数的POST请求

http://blog.youkuaiyun.com/jadyer/article/details/7615830     package  com.jadyer.util;      import  java.io.IOException;   import  java.io.UnsupportedEncodingException;   impo...

whywordonly的专栏 873

完整的Httpclient工具类发送带params和Header的post和get请求

1.HttpClient工具类 public class HttpClientUtils { /** 带请求头的get请求 **/ public static String doGet(String url) throws IOException { CloseableHttpClient client=null; CloseableHttpRespo...

qq_44742816的博客 4386
上一篇: 一文读懂MySQL的binLog日志
下一篇: maven打包SpringBoot工程忽略指定文件
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT小白架构师之路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值