百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

Java 实现 HTTP 请求的三种方式(java http post请求)

toyiye 2024-07-11 00:42 13 浏览 0 评论

  • 第一种方式:java原生HttpURLConnection
  • 第二种方式:apache HttpClient3.1
  • 第三种方式:apache httpClient4.5

除了本文推荐的几种方式,强烈推荐 OkHttp

目前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();
 // 设置连接方式: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;
 }
} 

第二种方式: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()];
 // 循环遍历参数集合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;
 }
} 

第三种方式: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方法获取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;
 }
} 

有时候我们在使用post请求时,可能传入的参数是json或者其他格式,此时我们则需要更改请求头及参数的设置信息,以httpClient4.5为例,更改下面两列配置:

httpPost.setEntity(new StringEntity("你的json串")); httpPost.addHeader("Content-Type", "application/json")。

来源:http://sina.lt/getG


:-D 搜索微信号(ID:芋道源码),可以获得各种 Java 源码解析、原理讲解、面试题、学习指南。

:-D 并且,回复【书籍】后,可以领取笔者推荐的各种 Java 从入门到架构的 100 本书籍。


相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码