java httpclient4.5_Apache HttpClient 4.5.3 使用详解

目录

环境准备

二进制 Jar 包

1、本文的 HttpClient 是指 Apache 官网 HttpComponents 项目下的子项目HttpClient 。

2、如果项目使用手动导入 Jar 包的方式,则可以从官网下载,地址:http://hc.apache.org/downloads.cgi

60ac39576bf1246421313a3619424cd2.png

6418379a5cdfd120a8acc4e155a8b89a.png

3、如果只是使用 HttpClient 做单纯的 get、post 等操作,则需导入下面红色框的几个包即可,另外几个是为了方便做其它操作而导入的。

a9f53cdb037a3dcb1930ec18eb9f5a8b.png

Maven 依赖

如下所示为 4.5.7 版本:

org.apache.httpcomponents

httpclient

4.5.7

Http get 请求

1、get 请求通常适用于请求对方的资源,或者类似做心跳的功能;如果是做有大量数据需要传输给对方时,应该采用 post 方式

import org.apache.commons.lang3.StringUtils;

import org.apache.http.HttpEntity;

import org.apache.http.StatusLine;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.config.RequestConfig;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.WinHttpClients;

import org.apache.http.util.EntityUtils;

import java.io.IOException;

import java.util.ResourceBundle;

/**

* Created by Administrator on 2018/5/30 0030.

* HttpClient工具类

*/

public final class HttpClientWmxUtils {

/**

* httpServerPath:Http默认连接的服务器地址,必须用http开头,例如 如下所示:

* http://192.168.1.20:8080/BaoAnCCAct/scheduleWmxController/clientRequest.action?clientFlag=1000

* 结尾可以用"?"分隔带参数

*/

private static final String httpServerPath;

static {

ResourceBundle resourceBundle = ResourceBundle.getBundle("systemConfig");

httpServerPath = resourceBundle.getString("httpServerPath");

}

/**

* get方式通常用于获取对方的数据

* 1、比如客户端用get方式连接服务器,查看是否有新的资源需要下载,如果有:则服务器返回资源;如果当前没有新资源下载,则返回消息告知即可

* 2、比如用get方式做简单的客户端心跳验证,如每个1分钟进行请求上报本地客户端状态

*/

public static final void httpGet() {

if (!WinHttpClients.isWinAuthAvailable()) {

System.out.println("Integrated Win auth is not supported!!!");

return;

}

if (StringUtils.isBlank(httpServerPath)) {

System.out.println("http 请求连接的ip为空,放弃连接");

return;

}

/** 创建CloseableHttpClient对象 * 官方推荐的创建HttpClient实例的方式 */

CloseableHttpClient httpclient = WinHttpClients.createDefault();

HttpGet httpget = new HttpGet(httpServerPath);

/** 设置超时时间、请求时间、socket时间都为5秒,允许重定向 */

RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)

.setConnectionRequestTimeout(5000)

.setSocketTimeout(5000)

.setRedirectsEnabled(true)

.build();

httpget.setConfig(requestConfig);

CloseableHttpResponse response = null;

try {

//如果连接不上服务器,则抛出:java.net.ConnectException: Connection refused: connect

response = httpclient.execute(httpget);

/** 获取返回的Http状态*/

StatusLine statusLine = response.getStatusLine();

int statusCode = statusLine.getStatusCode();

System.out.println("statusCode:" + statusCode); /**200(表示连接成功)*/

if (statusCode == 200) { /**获取服务器返回的文本消息*/HttpEntity httpEntity = response.getEntity();

String feedback = EntityUtils.toString(httpEntity, "UTF-8");

System.out.println("feedback:" + feedback);

}

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

/** 关闭输入流 */

try {

if (response != null) {

EntityUtils.consume(response.getEntity());

response.close();

}

} catch (IOException e) {

e.printStackTrace();

} /** * 无论成功与否,都要释放连接,终止连接 */

if (httpget != null && !httpget.isAborted()) {

httpget.releaseConnection();

httpget.abort();

}

if (httpclient != null) {

try {

httpclient.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

public static void main(String[] args) {

httpGet();

}

}

2、服务端接收代码示范如下,服务端像处理正常的浏览器请求即可,与 JS中 的 ajax 请求处理完全一致:

/**

* Created by Administrator on 2018/5/24 0024.

* 日程控制层

*/

@Controller()

@RequestMapping("scheduleWmxController")

public class ScheduleWmxController {

/**

* 用于信息发布客户端连接

*/

@RequestMapping(value = "clientRequest.action", method = RequestMethod.GET)

public static final void clientRequest(HttpServletRequest request, HttpServletResponse response) {

try {

response.setContentType("text/html;charset=UTF-8");

PrintWriter printWriter = response.getWriter();

/**获取客户端发来的消息*/

String userFlag = request.getParameter("userFlag");

System.out.println("userFlag:"+userFlag);

JsonObject feedbackJsonObject = new JsonObject();

feedbackJsonObject.addProperty("msgType", "success");

printWriter.write(feedbackJsonObject.toString());

printWriter.flush();

printWriter.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

运行结果如下:

e1ac809c40a0953a96e033ab9b8b9ec7.png

03ce0597177a0c92d0f30594596048f4.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值