APP下载

Java 实现 HTTP 请求的三种方式

消息来源:baojiabao.com 作者: 发布时间:2026-05-23

报价宝综合消息Java 实现 HTTP 请求的三种方式

第一种方式: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(" ");

}

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(" ");

}

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(" ");

}

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 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> entrySet = paramMap.entrySet();

// 获取迭代器

Iterator> iterator = entrySet.iterator();

int index = 0;

while (iterator.hasNext()) {

Entry 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(" ");

}

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 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 nvps = new ArrayList();

// 通过map整合entrySet方法获取entity

Set> entrySet = paramMap.entrySet();

// 循环遍历,获取迭代器

Iterator> iterator = entrySet.iterator();

while (iterator.hasNext()) {

Entry 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 本书籍。

来吧,骚年~

2019-12-17 10:54:00

相关文章