原生HttpClient详细使用示例
一、HttpClient类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL; public class HttpClient {
public static String doGet(String httpurl) {
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
String result = null;// 返回结果字符串
try {
// 创建远程url连接对象
URL url = new URL(httpurl);
// 通过远程url连接对象打开一个连接,强转成httpURLConnection类
connection = (HttpURLConnection) url.openConnection();
// 设置连接方式:get
connection.setRequestMethod("GET");
// 设置连接主机服务器的超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取远程返回的数据时间:60000毫秒
connection.setReadTimeout(60000);
// 发送请求
connection.connect();
// 通过connection连接,获取输入流
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// 封装输入流is,并指定字符集
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// 存放数据
StringBuffer sbf = new StringBuffer();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
} if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
} connection.disconnect();// 关闭远程连接
} return result;
} public static String doPost(String httpUrl, String param) { HttpURLConnection connection = null;
InputStream is = null;
OutputStream os = null;
BufferedReader br = null;
String result = null;
try {
URL url = new URL(httpUrl);
// 通过远程url连接对象打开连接
connection = (HttpURLConnection) url.openConnection();
// 设置连接请求方式
connection.setRequestMethod("POST");
// 设置连接主机服务器超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取主机服务器返回数据超时时间:60000毫秒
connection.setReadTimeout(60000); // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
connection.setDoOutput(true);
// 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
connection.setDoInput(true);
// 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
// 通过连接对象获取一个输出流
os = connection.getOutputStream();
// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
os.write(param.getBytes());
// 通过连接对象获取一个输入流,向远程读取
if (connection.getResponseCode() == 200) { is = connection.getInputStream();
// 对输入流对象进行包装:charset根据工作项目组的要求来设置
br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer sbf = new StringBuffer();
String temp = null;
// 循环遍历一行一行读取数据
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 断开与远程地址url的连接
connection.disconnect();
}
return result;
}
}
二、main方法
import java.util.Date; public class Main { public static void main(String[] args) {
str = HttpClient.doPost("https://www.baidu.com?tstmp="+Math.random(),"p=1");
System.out.println(str);
} }
原生HttpClient详细使用示例的更多相关文章
- oracle中to_date详细用法示例(oracle日期格式转换)
这篇文章主要介绍了oracle中to_date详细用法示例,包括期和字符转换函数用法.字符串和时间互转.求某天是星期几.两个日期间的天数.月份差等用法 TO_DATE格式(以时间:2007-11-02 ...
- MySQL备份与还原详细过程示例
MySQL备份与还原详细过程示例 一.MySQL备份类型 1.热备份.温备份.冷备份 (根据服务器状态) 热备份:读.写不受影响: 温备份:仅可以执行读操作: 冷备份:离线备份:读.写操作均中止: 2 ...
- httpclient详细介绍
1.HttpClient简介 HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 ...
- React Native:使用 JavaScript 构建原生应用 详细剖析
数月前,Facebook 对外宣布了正在开发的 React Native 框架,这个框架允许你使用 JavaScript 开发原生的 iOS 应用——就在今天,Beta 版的仓库释出了! 基于 Pho ...
- HttpClient配置及示例代码
HttpComponents是Apache 旗下的项目.其中有一个HttpClient,即HTTP客户端. ... ... 大多时候我们只需要HttpClient,httpCore是开发服务端的我们可 ...
- ZooKeeper(3.4.5) - 原生 API 的简单示例
一.创建会话 1. 创建一个基本的ZooKeeper会话实例 package com.huey.dream.demo; import java.util.concurrent.CountDownLat ...
- JAVA: httpclient 详细说明——第四章;
httpclient 具体解释--第一章. httpclient 具体解释--第二章: httpclient 具体解释--第三章: httpclient 具体解释--第四章: httpclient 具 ...
- HttpClient详细解释
Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且 ...
- java 原生 HttpClient
package org.rx.socks.http; import com.google.common.base.Strings; import lombok.SneakyThrows; import ...
随机推荐
- git 忽略部分文件类型的同步
场景 利用 pycharm 进行代码操作的时候会自动创建 .idea/ 文件夹 特么我每次随便做点操作.这里面的东西也会随着自动改一些 一开始开始无视 如果是多人协同开发会导致代码合并相关的问题 因此 ...
- nginx编译安装指定参数
--prefix=/app/nginx # 安装目录 --conf-path=/app/nginx/conf/nginx.conf # 配置文件 --sbin-path=/app/nginx/sbin ...
- 【转】Esp8266学习之旅① 搭建开发环境,开始一个“hellow world”串口打印。
@2019-02-28 [小记] Esp8266学习之旅① 搭建开发环境,开始一个“hellow world”串口打印.
- python版接口自动化测试框架源码完整版(requests + unittest)
python版接口自动化测试框架:https://gitee.com/UncleYong/my_rf [框架目录结构介绍] bin: 可执行文件,程序入口 conf: 配置文件 core: 核心文件 ...
- [模板]Min_25筛
用途 快速($O(\frac{n^{3/4}}{logn})$)地计算一些函数f的前缀和,以及(作为中间结果的)只计算质数的前缀和 一般要求f(p)是积性函数,$f(p)$是多项式的形式,且$f(p^ ...
- TensorFlow迁移学习的识别花试验
最近学习了TensorFlow,发现一个模型叫vgg16,然后搭建环境跑了一下,觉得十分神奇,而且准确率十分的高.又上了一节选修课,关于人工智能,老师让做一个关于人工智能的试验,于是觉得vgg16很不 ...
- Qt: 非阻塞时间延迟;
1.使用时间耗损循环: #include <QTime> ... QTime delayTime = QTime::currentTime().addMSecs(1000); while( ...
- DirectX11 With Windows SDK--12 深度/模板状态、平面镜反射绘制
前言 深度/模板测试使用的是与后备缓冲区同等分辨率大小的缓冲区,每个元素的一部分连续位用于深度测试,其余的则用作模板测试.两个测试的目的都是为了能够根据深度/模板状态需求的设置来选择需要绘制的像素. ...
- 33. Springboot 系列 原生方式引入Redis,非RedisTemplate
0.pom.xml <dependency> <groupId>redis.clients</groupId> <artifactId>jedis&l ...
- jpa/hibernate @onetomany 使用left join 添加多条件,可以使用过滤器filters (with-clause not allowed on fetched associations; use filters异常信息)
package com.ipinyou.mip.dataAsset.campaignManagement.entity; import com.ipinyou.mip.utils.NumberUtil ...