java实现HTTP请求的三种方式

From: https://www.cnblogs.com/hhhshct/p/8523697.html

  目前JAVA实现HTTP请求的方法用的最多的有两种:一种是通过HTTPClient这种第三方的开源框架去实现。HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,HttpClient3.1 是 org.apache.commons.httpclient下操作远程 url的工具包,虽然已不再更新,但实现工作中使用httpClient3.1的代码还是很多,HttpClient4.5是org.apache.http.client下操作远程 url的工具包,最新的;另一种则是通过HttpURLConnection去实现,HttpURLConnection是JAVA的标准类,是JAVA比较原生的一种实现方式。

  自己在工作中三种方式都用到过,总结一下分享给大家,也方便自己以后使用,话不多说上代码。

  第一种方式:java原生HttpURLConnection

  

复制代码

package com.powerX.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();// 设置连接方式:getconnection.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,当向远程服务器传送数据/写数据时,需要设置为trueconnection.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-ee040be542c0connection.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 HttpClient3.1

复制代码

package com.powerX.httpClient;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()];// 循环遍历参数集合mapSet<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;}
}

复制代码

  第三种方式:apache  httpClient4.5

复制代码

package com.powerX.httpClient;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方法获取entitySet<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;}
}

复制代码

  有时候我们在使用post请求时,可能传入的参数是json或者其他格式,此时我们则需要更改请求头及参数的设置信息,以httpClient4.5为例,更改下面两列配置:httpPost.setEntity(new StringEntity("你的json串"));      httpPost.addHeader("Content-Type", "application/json")。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/402616.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ActiveMQ queue 代码示例

生产者&#xff1a; package com.111.activemq;import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessa…

SpringBoot时间戳与MySql数据库记录相差14小时排错

From: http://www.cnblogs.com/jason1990/archive/2018/11/28/10032181.html 项目中遇到存储的时间戳与真实时间相差14小时的现象,以下为解决步骤. 问题 CREATE TABLE incident (id int(11) NOT NULL AUTO_INCREMENT,created_time timestamp NOT NULL DEFAULT CURRENT_TIMES…

HDU 1233 还是畅通工程(最小生成树)

传送门 还是畅通工程 Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 41447 Accepted Submission(s): 18920 Description 某省调查乡村交通状况&#xff0c;得到的统计表中列出了任意两村庄间的距离。省政府“畅…

出了本练内功的书:《完美软件开发:方法与逻辑》

首先说下什么叫“完美软件开发”&#xff0c;想象一下&#xff0c;完美的圆在现实中是不存在的&#xff0c;现实中的圆只能是对完美的圆的回归&#xff0c;但完美的圆描述了圆的构成规则&#xff0c;完美软件开发意义与此相同&#xff0c;它试图描述软件开发的规则和铁律。但既…

Springboot后台接收前端Date类型

From: https://my.oschina.net/zicheng/blog/2963117 这个问题不是专门针对Springboot的&#xff0c;Springmvc也同样适用于这一个问题。 昨的是Springboot前后端分离的项目&#xff0c;今天和前端对接口发现前端的请求走不到后台&#xff0c;检查了请求什么的都没有问题&…

关于jTopo的引用

jTopo是一款 2 D和3D模型展示的插件&#xff0c;不过目前文档不是很齐全&#xff0c;刚开始看的时候就有点懵了&#xff0c;因为你在网上很难找到jTopo的资料。下面我就介绍一下jTopo 的引用吧。 1、首先在官网上下载到jTopo的包&#xff0c;地址&#xff1a;http://www.jtopo.…

mysql重置root密码方法

2019独角兽企业重金招聘Python工程师标准>>> 1. 先关闭mysqld 2. 运行&#xff1a; mysqld_safe --skip-grant-tables 3. 另开一个窗口&#xff0c;用 mysql -uroot 登录mysql&#xff0c;执行 UPDATE mysql.user SET PasswordPASSWORD(你的密码) WHERE User…

插入排序之C++实现

描述 插入排序是一种简单直观的排序算法。它的基本思想是将一个待排序的数据序列分为已排序和未排序两部分&#xff0c;每次从未排序序列中取出一个元素&#xff0c;然后将它插入到已排序序列的适当位置&#xff0c;直到所有元素都插入完毕&#xff0c;即完成排序。 实现思路…

spring boot使用logback实现多环境日志配置

From: https://blog.csdn.net/vitech/article/details/53812137 软件生存周期中&#xff0c;涉及代码运行的环节有编码、测试和维护阶段&#xff0c;而一套成熟的代码&#xff0c;在此三个阶段&#xff0c;数据库、日志路径、日志级别、线程池大小等配置一般会不一样。作为开发…

IOT(Index Organized Table)

我们知道一般的表都以堆(heap)的形式来组织的&#xff0c;这是无序的组织方式。Oracle还提供了一种有序的表&#xff0c;它就是索引组织表&#xff0c;简称IOT表。IOT表上必须要有主键&#xff0c;而IOT表本身不对应segment&#xff0c;表里所有的数据都存放在主键所在的索引的…

C++中的 :: 用法

::是运算符中等级最高的&#xff0c;它分为三种:1)global scope(全局作用域符&#xff09;&#xff0c;用法&#xff08;::name)2)class scope(类作用域符&#xff09;&#xff0c;用法(class::name)3)namespace scope(命名空间作用域符&#xff09;&#xff0c;用法(namespace…

Spring Boot SLF4J日志实例

From: https://blog.csdn.net/lxh18682851338/article/details/78560295 默认情况下&#xff0c;SLF4j日志记录包含在Spring Boot Web应用程序中&#xff0c;只需要启用它就可以了。 注意&#xff1a;查看此Spring Boot Logback XML模板以了解默认的日志记录模式和配置。 SLF4…

java 反取字符串

public class demo2 {/*** 2 : 将字符串反取出来 新中国好 好国中新*/public static void main(String[] args) {String s "新中国好";s reverse1(s);System.out.println("方法一&#xff1a;" s);s reverse2(s);System.out.println("方法二…

测试使用wiz来发布blog

晚上尝试了下用wiz写随笔并发布&#xff0c;貌似成功了&#xff0c;虽然操作体验和方便性上不如word&#xff0c;但起码它集成了这个简单的功能可以让我用&#xff1a;如果能让我自动新建blog文章并自动定时更新发布就完美了。2013年7月5日19:31:04发现最近开始慢慢重度使用wiz…

Spring在Java Filter注入Bean为Null的问题解决

From: https://www.cnblogs.com/EasonJim/p/7666009.html 在Spring的自动注入中普通的POJO类都可以使用Autowired进行自动注入&#xff0c;但是除了两类&#xff1a;Filter和Servlet无法使用自动注入属性。&#xff08;因为这两个归Web容器管理&#xff09;可以用init&#xf…

关于工作的选择之软件开发还是软件维护的建议

今天是周六休息&#xff0c;好可爱的双休日啊。下周一出差去四平&#xff0c;要和我们单位另外2名工程师一起去给四平的一个公司安装调试一个机房的设备&#xff0c;大概需要三天的时间吧。昨天晚上去个朋友家做客&#xff0c;朋友他侄子大学是学计算机软件的&#xff0c;今年刚…

Mybatis:resultMap的使用总结

From: https://www.cnblogs.com/kenhome/p/7764398.html Mybatis的介绍以及使用&#xff1a;http://www.mybatis.org/mybatis-3/zh/index.html resultMap是Mybatis最强大的元素&#xff0c;它可以将查询到的复杂数据&#xff08;比如查询到几个表中数据&#xff09;映射到一个…

NSOperation, NSOperationQueue 原理探析

通过GNUstep的Foundation来尝试探索下NSOperation&#xff0c;NSOperationQueue 示例程序 写一个简单的程序 - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self configurationQueue]; LDNSOperatio…

MyBatis总结六:resultMap详解(包含多表查询)

From: https://www.cnblogs.com/Alex-zqzy/p/9296039.html 简介&#xff1a;   MyBatis的每一个查询映射的返回类型都是ResultMap&#xff0c;只是当我们提供的返回类型属性是resultType的时候&#xff0c;MyBatis对自动的给我们把对应的值赋给resultType所指定对象的属性&a…

object c 快速构建对象

__block NSNumber *capacity (0);