Java实现Http请求的常用方式
一、使用Java自带的java.io和java.net包。
实现方式如下:
- public class HttpClient {
//1、doGet方法- 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;
- }
- //2、doPost方法
- 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(150000);
- // 设置读取主机服务器返回数据超时时间:60000毫秒
- connection.setReadTimeout(600000);
- // 默认值为: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;
- }
二、使用Apache的HttpClient-4.x.Jar包。
Jar包Maven下载地址:https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient。
实现方式如下:
- package com.test.http;
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- import java.util.Map.Entry;
- import java.util.Set;
- import org.apache.http.HttpEntity;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.ClientProtocolException;
- 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.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClients;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.util.EntityUtils;
- public class HttpClient4 {
- public static String doGet(String url) {
- CloseableHttpClient httpClient = null;
- CloseableHttpResponse response = null;
- String result = "";
- try {
- // 通过址默认配置创建一个httpClient实例
- httpClient = HttpClients.createDefault();
- // 创建httpGet远程连接实例
- HttpGet httpGet = new HttpGet(url);
- // 设置请求头信息,鉴权
- httpGet.setHeader("Authorization",
- "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
- // 设置配置请求参数
- RequestConfig requestConfig = RequestConfig.custom()
- .setConnectTimeout(35000)// 连接主机服务超时时间
- .setConnectionRequestTimeout(35000)// 请求超时时间
- .setSocketTimeout(60000)// 数据读取超时时间
- .build();
- // 为httpGet实例设置配置
- httpGet.setConfig(requestConfig);
- // 执行get请求得到返回对象
- response = httpClient.execute(httpGet);
- // 通过返回对象获取返回数据
- HttpEntity entity = response.getEntity();
- // 通过EntityUtils中的toString方法将结果转换为字符串
- result = EntityUtils.toString(entity);
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- // 关闭资源
- if (null != response) {
- try {
- response.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (null != httpClient) {
- try {
- httpClient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return result;
- }
- public static String doPost(String url, Map<String, Object> paramMap) {
- CloseableHttpClient httpClient = null;
- CloseableHttpResponse httpResponse = null;
- String result = "";
- // 创建httpClient实例
- httpClient = HttpClients.createDefault();
- // 创建httpPost远程连接实例
- HttpPost httpPost = new HttpPost(url);
- // 配置请求参数实例
- RequestConfig requestConfig = RequestConfig.custom()
- .setConnectTimeout(35000)// 设置连接主机服务超时时间
- .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
- .setSocketTimeout(60000)// 设置读取数据连接超时时间
- .build();
- // 为httpPost实例设置配置
- httpPost.setConfig(requestConfig);
- // 设置请求头
- httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
- // 封装post请求参数
- if (null != paramMap && paramMap.size() > 0) {
- List<NameValuePair> nvps = new ArrayList<NameValuePair>();
- // 通过map集成entrySet方法获取entity
- Set<Entry<String, Object>> entrySet = paramMap.entrySet();
- // 循环遍历,获取迭代器
- Iterator<Entry<String, Object>> iterator = entrySet.iterator();
- while (iterator.hasNext()) {
- Entry<String, Object> mapEntry = iterator.next();
- nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry
- .getValue().toString()));
- }
- // 为httpPost设置封装好的请求参数
- try {
- httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- }
- try {
- // httpClient对象执行post请求,并返回响应参数对象
- httpResponse = httpClient.execute(httpPost);
- // 从响应对象中获取响应内容
- HttpEntity entity = httpResponse.getEntity();
- result = EntityUtils.toString(entity);
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- // 关闭资源
- if (null != httpResponse) {
- try {
- httpResponse.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (null != httpClient) {
- try {
- httpClient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return result;
- }
- }
三、使用Apache的HttpClient-3.x.Jar包。
Jar包Maven下载地址:https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient。
实现方式如下:
- package com.test.http;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.UnsupportedEncodingException;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Map.Entry;
- import java.util.Set;
- import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
- import org.apache.commons.httpclient.HttpClient;
- import org.apache.commons.httpclient.HttpStatus;
- import org.apache.commons.httpclient.NameValuePair;
- import org.apache.commons.httpclient.methods.GetMethod;
- import org.apache.commons.httpclient.methods.PostMethod;
- import org.apache.commons.httpclient.params.HttpMethodParams;
- public class HttpClient3 {
- public static String doGet(String url) {
- // 输入流
- InputStream is = null;
- BufferedReader br = null;
- String result = null;
- // 创建httpClient实例
- HttpClient httpClient = new HttpClient();
- // 设置http连接主机服务超时时间:15000毫秒
- // 先获取连接管理器对象,再获取参数对象,再进行参数的赋值
- httpClient.getHttpConnectionManager().getParams()
- .setConnectionTimeout(15000);
- // 创建一个Get方法实例对象
- GetMethod getMethod = new GetMethod(url);
- // 设置get请求超时为60000毫秒
- getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
- // 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反
- getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
- new DefaultHttpMethodRetryHandler(3, true));
- try {
- // 执行Get方法
- int statusCode = httpClient.executeMethod(getMethod);
- // 判断返回码
- if (statusCode != HttpStatus.SC_OK) {
- // 如果状态码返回的不是ok,说明失败了,打印错误信息
- System.err
- .println("Method faild: " + getMethod.getStatusLine());
- } else {
- // 通过getMethod实例,获取远程的一个输入流
- is = getMethod.getResponseBodyAsStream();
- // 包装输入流
- br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
- StringBuffer sbf = new StringBuffer();
- // 读取封装的输入流
- String temp = null;
- while ((temp = br.readLine()) != null) {
- sbf.append(temp).append("\r\n");
- }
- result = sbf.toString();
- }
- } 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();
- }
- }
- // 释放连接
- getMethod.releaseConnection();
- }
- return result;
- }
- public static String doPost(String url, Map<String, Object> paramMap) {
- // 获取输入流
- InputStream is = null;
- BufferedReader br = null;
- String result = null;
- // 创建httpClient实例对象
- HttpClient httpClient = new HttpClient();
- // 设置httpClient连接主机服务器超时时间:15000毫秒
- httpClient.getHttpConnectionManager().getParams()
- .setConnectionTimeout(15000);
- // 创建post请求方法实例对象
- PostMethod postMethod = new PostMethod(url);
- // 设置post请求超时时间
- postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
- NameValuePair[] nvp = null;
- // 判断参数map集合paramMap是否为空
- if (null != paramMap && paramMap.size() > 0) {// 不为空
- // 创建键值参数对象数组,大小为参数的个数
- nvp = new NameValuePair[paramMap.size()];
- // 循环遍历参数集合map
- Set<Entry<String, Object>> entrySet = paramMap.entrySet();
- // 获取迭代器
- Iterator<Entry<String, Object>> iterator = entrySet.iterator();
- int index = 0;
- while (iterator.hasNext()) {
- Entry<String, Object> mapEntry = iterator.next();
- // 从mapEntry中获取key和value创建键值对象存放到数组中
- try {
- nvp[index] = new NameValuePair(mapEntry.getKey(),
- new String(mapEntry.getValue().toString()
- .getBytes("UTF-8"), "UTF-8"));
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- index++;
- }
- }
- // 判断nvp数组是否为空
- if (null != nvp && nvp.length > 0) {
- // 将参数存放到requestBody对象中
- postMethod.setRequestBody(nvp);
- }
- // 执行POST方法
- try {
- int statusCode = httpClient.executeMethod(postMethod);
- // 判断是否成功
- if (statusCode != HttpStatus.SC_OK) {
- System.err.println("Method faild: "
- + postMethod.getStatusLine());
- }
- // 获取远程返回的数据
- is = postMethod.getResponseBodyAsStream();
- // 封装输入流
- br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
- StringBuffer sbf = new StringBuffer();
- String temp = null;
- while ((temp = br.readLine()) != null) {
- sbf.append(temp).append("\r\n");
- }
- result = sbf.toString();
- } 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();
- }
- }
- // 释放连接
- postMethod.releaseConnection();
- }
- return result;
- }
- }
Java实现Http请求的常用方式的更多相关文章
- PHP中使用POST发送请求的常用方式
前提概要: 在PHP进行项目开发过程中,使用post发送请求的情况很多,以下总结了项目中主要用的两种方式. 总结下: 在我接触到的项目中用到第二种情况较多,比如写:短信接口.....总体来说比较简单便 ...
- java实现HTTP请求的三种方式
目前JAVA实现HTTP请求的方法用的最多的有两种:一种是通过HTTPClient这种第三方的开源框架去实现.HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,Ht ...
- iOS- 网络请求的两种常用方式【GET & POST】的区别
GET和POST 网络请求的两种常用方式的实现[GET & POST] –GET的语义是获取指定URL上的资源 –将数据按照variable=value的形式,添加到action所指向的URL ...
- 【转载】java实现HTTP请求的三种方式
目前JAVA实现HTTP请求的方法用的最多的有两种:一种是通过HTTPClient这种第三方的开源框架去实现.HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,Ht ...
- HTTP:Java实现HTTP请求的三种方式
目前JAVA实现HTTP请求的方法用的最多的有两种: 一种是通过HTTPClient这种第三方的开源框架去实现.HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,H ...
- Java Web乱码分析及解决方式(二)——POST请求乱码
引言 GET请求的本质表现是将请求參数放在URL地址栏中.form表单的Method为GET的情况.參数会被浏览器默认编码,所以乱码处理方案是一样的. 对于POST请求乱码.解决起来要比GET简单.我 ...
- Java调用第三方http接口的方式
1. 概述 在实际开发过程中,我们经常需要调用对方提供的接口或测试自己写的接口是否合适.很多项目都会封装规定好本身项目的接口规范,所以大多数需要去调用对方提供的接口或第三方接口(短信.天气等). 在J ...
- XML基础+Java解析XML +几种解析方式的性能比较
XML基础+Java解析XML 一:XML基础 XML是什么: 可扩展的标记语言 XML能干什么: 描述数据.存储数据.传输(交换)数据. XML与HTML区别: 目的不一样 XML 被设计用来描述数 ...
- 一个java的http请求的封装工具类
java实现http请求的方法常用有两种,一种则是通过java自带的标准类HttpURLConnection去实现,另一种是通过apache的httpclient去实现.本文用httpclient去实 ...
随机推荐
- 你不知道的JavaScript--Item19 执行上下文(execution context)
在这篇文章里,我将深入研究JavaScript中最基本的部分--执行上下文(execution context).读完本文后,你应该清楚了解释器做了什么,为什么函数和变量能在声明前使用以及他们的值是如 ...
- javascript 事件编程之事件(流,处理,对象,类型)
1. 事件处理 1.1. 绑定事件方式 1)行内绑定 语法: //最常用的使用方式 <元素 事件="事件处理程序"> 2)动态绑定 //结构+样式+行为分离的页面(ht ...
- css3绘制三角形
将div的宽和高设置为0:利用border-width.border-style.border-color属性绘制不同位置边框的样式.将不需要展示的三角颜色填充为transparent透明即可,就能得 ...
- 用 150 行 Python 代码写的量子计算模拟器
简评:让你更轻松地明白,量子计算机如何遵循线性代数计算的. 这是个 GItHub 项目,可以简单了解一下. qusim.py 是一个多量子位的量子计算机模拟器(玩具?),用 150 行的 python ...
- windows7 dos修改mysql root密码
第一步:打开mysql 安装路径 选择bin文件 同时按下Shift+鼠标右键 点击"在此处打开命令" 第二步:输入mysql -u root -p 按回车键会提示输入密码 ...
- compact_op.go
package clientv3 import ( pb "github.com/coreos/etcd/etcdserver/etcdserverpb" ) // Com ...
- bzoj 1098 poi2007 办公楼 bfs+链表
题意很好理解,求给出图反图的联通块个数. 考虑这样一个事情:一个联通块里的点,最多只会被遍历一次,再遍历时没有任何意义 所以用链表来存,每遍历到一个点就将该点删掉 #include<cstdio ...
- BZOJ_2734_[HNOI2012]集合选数_构造+状压DP
BZOJ_2734_[HNOI2012]集合选数_构造+状压DP 题意:<集合论与图论>这门课程有一道作业题,要求同学们求出{1, 2, 3, 4, 5}的所有满足以 下条件的子集:若 x ...
- BZOJ_1455_罗马游戏_可并堆
BZOJ_1455_罗马游戏_可并堆 Description 罗马皇帝很喜欢玩杀人游戏. 他的军队里面有n个人,每个人都是一个独立的团.最近举行了一次平面几何测试,每个人都得到了一个分数. 皇帝很喜欢 ...
- BZOJ_2724_[Violet 6]蒲公英_分块
BZOJ_2724_[Violet 6]蒲公英_分块 Description Input 修正一下 l = (l_0 + x - 1) mod n + 1, r = (r_0 + x - 1) mod ...