一、使用Java自带的java.io和java.net包。

  实现方式如下:

  1. public class HttpClient {
         //1、doGet方法 
  2. public static String doGet(String httpurl) {
  3. HttpURLConnection connection = null;
  4. InputStream is = null;
  5. BufferedReader br = null;
  6. String result = null;// 返回结果字符串
  7. try {
  8. // 创建远程url连接对象
  9. URL url = new URL(httpurl);
  10. // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
  11. connection = (HttpURLConnection) url.openConnection();
  12. // 设置连接方式:get
  13. connection.setRequestMethod("GET");
  14. // 设置连接主机服务器的超时时间:15000毫秒
  15. connection.setConnectTimeout(15000);
  16. // 设置读取远程返回的数据时间:60000毫秒
  17. connection.setReadTimeout(60000);
  18. // 发送请求
  19. connection.connect();
  20. // 通过connection连接,获取输入流
  21. if (connection.getResponseCode() == 200) {
  22. is = connection.getInputStream();
  23. // 封装输入流is,并指定字符集
  24. br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
  25. // 存放数据
  26. StringBuffer sbf = new StringBuffer();
  27. String temp = null;
  28. while ((temp = br.readLine()) != null) {
  29. sbf.append(temp);
  30. sbf.append("\r\n");
  31. }
  32. result = sbf.toString();
  33. }
  34. } catch (MalformedURLException e) {
  35. e.printStackTrace();
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. } finally {
  39. // 关闭资源
  40. if (null != br) {
  41. try {
  42. br.close();
  43. } catch (IOException e) {
  44. e.printStackTrace();
  45. }
  46. }
  47.  
  48. if (null != is) {
  49. try {
  50. is.close();
  51. } catch (IOException e) {
  52. e.printStackTrace();
  53. }
  54. }
  55.  
  56. connection.disconnect();// 关闭远程连接
  57. }
  58.  
  59. return result;
  60. }
  61.      //2、doPost方法
  62. public static String doPost(String httpUrl, String param) {
  63.  
  64. HttpURLConnection connection = null;
  65. InputStream is = null;
  66. OutputStream os = null;
  67. BufferedReader br = null;
  68. String result = null;
  69. try {
  70. URL url = new URL(httpUrl);
  71. // 通过远程url连接对象打开连接
  72. connection = (HttpURLConnection) url.openConnection();
  73. // 设置连接请求方式
  74. connection.setRequestMethod("POST");
  75. // 设置连接主机服务器超时时间:15000毫秒
  76. connection.setConnectTimeout(150000);
  77. // 设置读取主机服务器返回数据超时时间:60000毫秒
  78. connection.setReadTimeout(600000);
  79.  
  80. // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
  81. connection.setDoOutput(true);
  82. // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
  83. connection.setDoInput(true);
  84. // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
  85. connection.setRequestProperty("Content-Type",
  86. "application/x-www-form-urlencoded");
  87. // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
  88. connection.setRequestProperty("Authorization",
  89. "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
  90. // 通过连接对象获取一个输出流
  91. os = connection.getOutputStream();
  92. // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
  93. os.write(param.getBytes());
  94. // 通过连接对象获取一个输入流,向远程读取
  95. if (connection.getResponseCode() == 200) {
  96. is = connection.getInputStream();
  97. // 对输入流对象进行包装:charset根据工作项目组的要求来设置
  98. br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
  99.  
  100. StringBuffer sbf = new StringBuffer();
  101. String temp = null;
  102. // 循环遍历一行一行读取数据
  103. while ((temp = br.readLine()) != null) {
  104. sbf.append(temp);
  105. sbf.append("\r\n");
  106. }
  107. result = sbf.toString();
  108. }
  109. } catch (MalformedURLException e) {
  110. e.printStackTrace();
  111. } catch (IOException e) {
  112. e.printStackTrace();
  113. } finally {
  114. // 关闭资源
  115. if (null != br) {
  116. try {
  117. br.close();
  118. } catch (IOException e) {
  119. e.printStackTrace();
  120. }
  121. }
  122. if (null != os) {
  123. try {
  124. os.close();
  125. } catch (IOException e) {
  126. e.printStackTrace();
  127. }
  128. }
  129. if (null != is) {
  130. try {
  131. is.close();
  132. } catch (IOException e) {
  133. e.printStackTrace();
  134. }
  135. }
  136. // 断开与远程地址url的连接
  137. connection.disconnect();
  138. }
  139. return result;
  140. }

  

二、使用Apache的HttpClient-4.x.Jar包。

  Jar包Maven下载地址:https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient

  实现方式如下:

  1. package com.test.http;
  2.  
  3. import java.io.IOException;
  4. import java.io.UnsupportedEncodingException;
  5. import java.util.ArrayList;
  6. import java.util.Iterator;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.Map.Entry;
  10. import java.util.Set;
  11.  
  12. import org.apache.http.HttpEntity;
  13. import org.apache.http.NameValuePair;
  14. import org.apache.http.client.ClientProtocolException;
  15. import org.apache.http.client.config.RequestConfig;
  16. import org.apache.http.client.entity.UrlEncodedFormEntity;
  17. import org.apache.http.client.methods.CloseableHttpResponse;
  18. import org.apache.http.client.methods.HttpGet;
  19. import org.apache.http.client.methods.HttpPost;
  20. import org.apache.http.impl.client.CloseableHttpClient;
  21. import org.apache.http.impl.client.HttpClients;
  22. import org.apache.http.message.BasicNameValuePair;
  23. import org.apache.http.util.EntityUtils;
  24.  
  25. public class HttpClient4 {
  26.  
  27. public static String doGet(String url) {
  28. CloseableHttpClient httpClient = null;
  29. CloseableHttpResponse response = null;
  30. String result = "";
  31. try {
  32. // 通过址默认配置创建一个httpClient实例
  33. httpClient = HttpClients.createDefault();
  34. // 创建httpGet远程连接实例
  35. HttpGet httpGet = new HttpGet(url);
  36. // 设置请求头信息,鉴权
  37. httpGet.setHeader("Authorization",
  38. "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
  39. // 设置配置请求参数
  40. RequestConfig requestConfig = RequestConfig.custom()
  41. .setConnectTimeout(35000)// 连接主机服务超时时间
  42. .setConnectionRequestTimeout(35000)// 请求超时时间
  43. .setSocketTimeout(60000)// 数据读取超时时间
  44. .build();
  45. // 为httpGet实例设置配置
  46. httpGet.setConfig(requestConfig);
  47. // 执行get请求得到返回对象
  48. response = httpClient.execute(httpGet);
  49. // 通过返回对象获取返回数据
  50. HttpEntity entity = response.getEntity();
  51. // 通过EntityUtils中的toString方法将结果转换为字符串
  52. result = EntityUtils.toString(entity);
  53. } catch (ClientProtocolException e) {
  54. e.printStackTrace();
  55. } catch (IOException e) {
  56. e.printStackTrace();
  57. } finally {
  58. // 关闭资源
  59. if (null != response) {
  60. try {
  61. response.close();
  62. } catch (IOException e) {
  63. e.printStackTrace();
  64. }
  65. }
  66. if (null != httpClient) {
  67. try {
  68. httpClient.close();
  69. } catch (IOException e) {
  70. e.printStackTrace();
  71. }
  72. }
  73. }
  74. return result;
  75. }
  76.  
  77. public static String doPost(String url, Map<String, Object> paramMap) {
  78. CloseableHttpClient httpClient = null;
  79. CloseableHttpResponse httpResponse = null;
  80. String result = "";
  81. // 创建httpClient实例
  82. httpClient = HttpClients.createDefault();
  83. // 创建httpPost远程连接实例
  84. HttpPost httpPost = new HttpPost(url);
  85. // 配置请求参数实例
  86. RequestConfig requestConfig = RequestConfig.custom()
  87. .setConnectTimeout(35000)// 设置连接主机服务超时时间
  88. .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
  89. .setSocketTimeout(60000)// 设置读取数据连接超时时间
  90. .build();
  91. // 为httpPost实例设置配置
  92. httpPost.setConfig(requestConfig);
  93. // 设置请求头
  94. httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
  95. // 封装post请求参数
  96. if (null != paramMap && paramMap.size() > 0) {
  97. List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  98. // 通过map集成entrySet方法获取entity
  99. Set<Entry<String, Object>> entrySet = paramMap.entrySet();
  100. // 循环遍历,获取迭代器
  101. Iterator<Entry<String, Object>> iterator = entrySet.iterator();
  102. while (iterator.hasNext()) {
  103. Entry<String, Object> mapEntry = iterator.next();
  104. nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry
  105. .getValue().toString()));
  106. }
  107.  
  108. // 为httpPost设置封装好的请求参数
  109. try {
  110. httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
  111. } catch (UnsupportedEncodingException e) {
  112. e.printStackTrace();
  113. }
  114. }
  115. try {
  116. // httpClient对象执行post请求,并返回响应参数对象
  117. httpResponse = httpClient.execute(httpPost);
  118. // 从响应对象中获取响应内容
  119. HttpEntity entity = httpResponse.getEntity();
  120. result = EntityUtils.toString(entity);
  121. } catch (ClientProtocolException e) {
  122. e.printStackTrace();
  123. } catch (IOException e) {
  124. e.printStackTrace();
  125. } finally {
  126. // 关闭资源
  127. if (null != httpResponse) {
  128. try {
  129. httpResponse.close();
  130. } catch (IOException e) {
  131. e.printStackTrace();
  132. }
  133. }
  134. if (null != httpClient) {
  135. try {
  136. httpClient.close();
  137. } catch (IOException e) {
  138. e.printStackTrace();
  139. }
  140. }
  141. }
  142. return result;
  143. }
  144. }

三、使用Apache的HttpClient-3.x.Jar包。

  Jar包Maven下载地址:https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient

  实现方式如下:

  1. package com.test.http;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.io.UnsupportedEncodingException;
  8. import java.util.Iterator;
  9. import java.util.Map;
  10. import java.util.Map.Entry;
  11. import java.util.Set;
  12.  
  13. import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
  14. import org.apache.commons.httpclient.HttpClient;
  15. import org.apache.commons.httpclient.HttpStatus;
  16. import org.apache.commons.httpclient.NameValuePair;
  17. import org.apache.commons.httpclient.methods.GetMethod;
  18. import org.apache.commons.httpclient.methods.PostMethod;
  19. import org.apache.commons.httpclient.params.HttpMethodParams;
  20.  
  21. public class HttpClient3 {
  22.  
  23. public static String doGet(String url) {
  24. // 输入流
  25. InputStream is = null;
  26. BufferedReader br = null;
  27. String result = null;
  28. // 创建httpClient实例
  29. HttpClient httpClient = new HttpClient();
  30. // 设置http连接主机服务超时时间:15000毫秒
  31. // 先获取连接管理器对象,再获取参数对象,再进行参数的赋值
  32. httpClient.getHttpConnectionManager().getParams()
  33. .setConnectionTimeout(15000);
  34. // 创建一个Get方法实例对象
  35. GetMethod getMethod = new GetMethod(url);
  36. // 设置get请求超时为60000毫秒
  37. getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
  38. // 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反
  39. getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
  40. new DefaultHttpMethodRetryHandler(3, true));
  41. try {
  42. // 执行Get方法
  43. int statusCode = httpClient.executeMethod(getMethod);
  44. // 判断返回码
  45. if (statusCode != HttpStatus.SC_OK) {
  46. // 如果状态码返回的不是ok,说明失败了,打印错误信息
  47. System.err
  48. .println("Method faild: " + getMethod.getStatusLine());
  49. } else {
  50. // 通过getMethod实例,获取远程的一个输入流
  51. is = getMethod.getResponseBodyAsStream();
  52. // 包装输入流
  53. br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
  54.  
  55. StringBuffer sbf = new StringBuffer();
  56. // 读取封装的输入流
  57. String temp = null;
  58. while ((temp = br.readLine()) != null) {
  59. sbf.append(temp).append("\r\n");
  60. }
  61.  
  62. result = sbf.toString();
  63. }
  64.  
  65. } catch (IOException e) {
  66. e.printStackTrace();
  67. } finally {
  68. // 关闭资源
  69. if (null != br) {
  70. try {
  71. br.close();
  72. } catch (IOException e) {
  73. e.printStackTrace();
  74. }
  75. }
  76. if (null != is) {
  77. try {
  78. is.close();
  79. } catch (IOException e) {
  80. e.printStackTrace();
  81. }
  82. }
  83. // 释放连接
  84. getMethod.releaseConnection();
  85. }
  86. return result;
  87. }
  88.  
  89. public static String doPost(String url, Map<String, Object> paramMap) {
  90. // 获取输入流
  91. InputStream is = null;
  92. BufferedReader br = null;
  93. String result = null;
  94. // 创建httpClient实例对象
  95. HttpClient httpClient = new HttpClient();
  96. // 设置httpClient连接主机服务器超时时间:15000毫秒
  97. httpClient.getHttpConnectionManager().getParams()
  98. .setConnectionTimeout(15000);
  99. // 创建post请求方法实例对象
  100. PostMethod postMethod = new PostMethod(url);
  101. // 设置post请求超时时间
  102. postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
  103.  
  104. NameValuePair[] nvp = null;
  105. // 判断参数map集合paramMap是否为空
  106. if (null != paramMap && paramMap.size() > 0) {// 不为空
  107. // 创建键值参数对象数组,大小为参数的个数
  108. nvp = new NameValuePair[paramMap.size()];
  109. // 循环遍历参数集合map
  110. Set<Entry<String, Object>> entrySet = paramMap.entrySet();
  111. // 获取迭代器
  112. Iterator<Entry<String, Object>> iterator = entrySet.iterator();
  113.  
  114. int index = 0;
  115. while (iterator.hasNext()) {
  116. Entry<String, Object> mapEntry = iterator.next();
  117. // 从mapEntry中获取key和value创建键值对象存放到数组中
  118. try {
  119. nvp[index] = new NameValuePair(mapEntry.getKey(),
  120. new String(mapEntry.getValue().toString()
  121. .getBytes("UTF-8"), "UTF-8"));
  122. } catch (UnsupportedEncodingException e) {
  123. e.printStackTrace();
  124. }
  125. index++;
  126. }
  127. }
  128. // 判断nvp数组是否为空
  129. if (null != nvp && nvp.length > 0) {
  130. // 将参数存放到requestBody对象中
  131. postMethod.setRequestBody(nvp);
  132. }
  133. // 执行POST方法
  134. try {
  135. int statusCode = httpClient.executeMethod(postMethod);
  136. // 判断是否成功
  137. if (statusCode != HttpStatus.SC_OK) {
  138. System.err.println("Method faild: "
  139. + postMethod.getStatusLine());
  140. }
  141. // 获取远程返回的数据
  142. is = postMethod.getResponseBodyAsStream();
  143. // 封装输入流
  144. br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
  145.  
  146. StringBuffer sbf = new StringBuffer();
  147. String temp = null;
  148. while ((temp = br.readLine()) != null) {
  149. sbf.append(temp).append("\r\n");
  150. }
  151.  
  152. result = sbf.toString();
  153. } catch (IOException e) {
  154. e.printStackTrace();
  155. } finally {
  156. // 关闭资源
  157. if (null != br) {
  158. try {
  159. br.close();
  160. } catch (IOException e) {
  161. e.printStackTrace();
  162. }
  163. }
  164. if (null != is) {
  165. try {
  166. is.close();
  167. } catch (IOException e) {
  168. e.printStackTrace();
  169. }
  170. }
  171. // 释放连接
  172. postMethod.releaseConnection();
  173. }
  174. return result;
  175. }
  176. }

  

 

Java实现Http请求的常用方式的更多相关文章

  1. PHP中使用POST发送请求的常用方式

    前提概要: 在PHP进行项目开发过程中,使用post发送请求的情况很多,以下总结了项目中主要用的两种方式. 总结下: 在我接触到的项目中用到第二种情况较多,比如写:短信接口.....总体来说比较简单便 ...

  2. java实现HTTP请求的三种方式

    目前JAVA实现HTTP请求的方法用的最多的有两种:一种是通过HTTPClient这种第三方的开源框架去实现.HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,Ht ...

  3. iOS- 网络请求的两种常用方式【GET & POST】的区别

    GET和POST 网络请求的两种常用方式的实现[GET & POST] –GET的语义是获取指定URL上的资源 –将数据按照variable=value的形式,添加到action所指向的URL ...

  4. 【转载】java实现HTTP请求的三种方式

    目前JAVA实现HTTP请求的方法用的最多的有两种:一种是通过HTTPClient这种第三方的开源框架去实现.HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,Ht ...

  5. HTTP:Java实现HTTP请求的三种方式

    目前JAVA实现HTTP请求的方法用的最多的有两种: 一种是通过HTTPClient这种第三方的开源框架去实现.HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,H ...

  6. Java Web乱码分析及解决方式(二)——POST请求乱码

    引言 GET请求的本质表现是将请求參数放在URL地址栏中.form表单的Method为GET的情况.參数会被浏览器默认编码,所以乱码处理方案是一样的. 对于POST请求乱码.解决起来要比GET简单.我 ...

  7. Java调用第三方http接口的方式

    1. 概述 在实际开发过程中,我们经常需要调用对方提供的接口或测试自己写的接口是否合适.很多项目都会封装规定好本身项目的接口规范,所以大多数需要去调用对方提供的接口或第三方接口(短信.天气等). 在J ...

  8. XML基础+Java解析XML +几种解析方式的性能比较

    XML基础+Java解析XML 一:XML基础 XML是什么: 可扩展的标记语言 XML能干什么: 描述数据.存储数据.传输(交换)数据. XML与HTML区别: 目的不一样 XML 被设计用来描述数 ...

  9. 一个java的http请求的封装工具类

    java实现http请求的方法常用有两种,一种则是通过java自带的标准类HttpURLConnection去实现,另一种是通过apache的httpclient去实现.本文用httpclient去实 ...

随机推荐

  1. 你不知道的JavaScript--Item19 执行上下文(execution context)

    在这篇文章里,我将深入研究JavaScript中最基本的部分--执行上下文(execution context).读完本文后,你应该清楚了解释器做了什么,为什么函数和变量能在声明前使用以及他们的值是如 ...

  2. javascript 事件编程之事件(流,处理,对象,类型)

    1. 事件处理 1.1. 绑定事件方式 1)行内绑定 语法: //最常用的使用方式 <元素 事件="事件处理程序"> 2)动态绑定 //结构+样式+行为分离的页面(ht ...

  3. css3绘制三角形

    将div的宽和高设置为0:利用border-width.border-style.border-color属性绘制不同位置边框的样式.将不需要展示的三角颜色填充为transparent透明即可,就能得 ...

  4. 用 150 行 Python 代码写的量子计算模拟器

    简评:让你更轻松地明白,量子计算机如何遵循线性代数计算的. 这是个 GItHub 项目,可以简单了解一下. qusim.py 是一个多量子位的量子计算机模拟器(玩具?),用 150 行的 python ...

  5. windows7 dos修改mysql root密码

    第一步:打开mysql 安装路径  选择bin文件  同时按下Shift+鼠标右键  点击"在此处打开命令" 第二步:输入mysql -u root -p 按回车键会提示输入密码 ...

  6. compact_op.go

    package clientv3 import (     pb "github.com/coreos/etcd/etcdserver/etcdserverpb" ) // Com ...

  7. bzoj 1098 poi2007 办公楼 bfs+链表

    题意很好理解,求给出图反图的联通块个数. 考虑这样一个事情:一个联通块里的点,最多只会被遍历一次,再遍历时没有任何意义 所以用链表来存,每遍历到一个点就将该点删掉 #include<cstdio ...

  8. BZOJ_2734_[HNOI2012]集合选数_构造+状压DP

    BZOJ_2734_[HNOI2012]集合选数_构造+状压DP 题意:<集合论与图论>这门课程有一道作业题,要求同学们求出{1, 2, 3, 4, 5}的所有满足以 下条件的子集:若 x ...

  9. BZOJ_1455_罗马游戏_可并堆

    BZOJ_1455_罗马游戏_可并堆 Description 罗马皇帝很喜欢玩杀人游戏. 他的军队里面有n个人,每个人都是一个独立的团.最近举行了一次平面几何测试,每个人都得到了一个分数. 皇帝很喜欢 ...

  10. BZOJ_2724_[Violet 6]蒲公英_分块

    BZOJ_2724_[Violet 6]蒲公英_分块 Description Input 修正一下 l = (l_0 + x - 1) mod n + 1, r = (r_0 + x - 1) mod ...