一、需求
通过JAVA实现一个代理服务器,客户端的Http请求全部指向代理服务器,代理服务器基于一定的策略将请求转发给后台服务器。
二、需求分析
需求可以简化为
1、代理服务主机将客户机与代理服务主机之间的请求截获,然后直接将信息转发给目标主机
2、代理服务主机将目标主机的回应直接转发给客户机。
代理服务主机可以通过socket直接获取客户机发送到本机指定端口的数据报文,那么通过分析内容可以得到客户机想要发送给目标主机的信息,代理服务主机可以通过socket的方式再次重新请求,将原来请求中的内容转发给目标主机,之后将目标主机的回应转发给客户机。
对于Java SE项目来说,有两者方式来实现:
1、采用原生的Java socket 编程。(存在多线程问题...)
2、采用第三方的网络应用框架,比如:mina、netty等。(开发简单,稳定可靠)
对于Java WEB项目来说,也有两者方式来实现:
1、采用上面的Java SE方案。
2、HTTP代理,拦截客户端的请求,并采用Http协议发送GET/POST请求给目标服务器。(这里又可以分三种种情况)
三、Demo实例
1、原先的socket代理百度上一大堆...
2、mina代理demo
3、netty代理demo
见:https://download.csdn.net/download/wqc19920906/10270714
4、Http代理服务器demo
发送http请求分别有
1)、用HttpURLConnection发送请求
2)、使用URLConnection发送请求
2)、使用HttpClient发送请求
4)、使用socket发送请求
详见:https://blog.csdn.net/u010197591/article/details/51441399
四、自己用的HttpClient代理。