前情提要
- 本文的HttpClient是指Apache官网HttpComponents项目下的子项目
- 文档当前使用的版本为4.5.3
项目新建
- 导入开发依赖的jar,HttpClient单纯的get、post等操作,只要导入下面红色框的即可,另外三个是为了方便做其它操作而导入的
客户端get请求
- 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!!!");
}
/** 创建CloseableHttpClient对象
* 官方推荐的创建HttpClient实例的方式
*/
if (StringUtils.isBlank(httpServerPath)) {
System.out.println("http 请求连接的ip为空,放弃连接");
return;
}
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 {
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 {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
/**
* 无论成功与否,都要释放连接,终止连接
*/
if (httpget != null && !httpget.isAborted()) {
httpget.releaseConnection();
httpget.abort();
}
/** 最后也要关闭XxxHttpResponse
*/
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpclient != null) {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
httpGet();
}
}
服务端接收
- 服务端像处理正常的浏览器请求即可,与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();
}
}
}
测试输出