Apache HttpClient 4.5.3 使用详解

目录

HttpClient 下载

Http get 请求


HttpClient 下载

二进制 Jar 包

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

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

Apache HttpClient 4.5.3 使用详解_第1张图片

Apache HttpClient 4.5.3 使用详解_第2张图片

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

Apache HttpClient 4.5.3 使用详解_第3张图片

Maven 依赖

如果是 Maven 项目,则可以从 Maven 中央仓库获取依赖:https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient

如下所示为 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();
        }
    }
}

运行结果如下:

Apache HttpClient 4.5.3 使用详解_第4张图片

Apache HttpClient 4.5.3 使用详解_第5张图片

 

你可能感兴趣的:(Http)