本例中,使用netty来进行http客户端的请求。
1.HttpClientDemo.java:启动客户端
package org.attempt.netty4.demo002;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import java.net.URL;
public class HttpClientDemo {
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
ResultHandler resultHandler = new ResultHandler(group);
private Channel getChannel(String url) throws Exception {
URL urlObj = new URL(url);
String host = urlObj.getHost();
int port = urlObj.getPort();
if(port == -1 && urlObj.getProtocol().equals("http")) {
port = 80;
}
if(port == -1 && urlObj.getProtocol().equals("https")) {
port = 443;
}
b.group(group)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel channel) throws Exception {
channel.pipeline()
//字符串解码和编码
.addLast(new StringDecoder())
.addLast(new StringEncoder())
//客户端的逻辑
.addLast(new HttpClientHandler(resultHandler));
}
});
return b.connect(host, port).sync().channel();
}
public void stop(EventLoopGroup group) {
if(null != group) {
//优雅退出,释放线程池资源
group.shutdownGracefully();
}
}
public String get(String url) throws Exception {
Channel channel = getChannel(url);
URL urlObj = new URL(url);
String path = urlObj.getPath();
if(path == "") {
path = "/";
}
String requestLine = "GET "+ path +" HTTP/1.1\n";
String header = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\n" +
"Accept-Encoding: gzip, deflate, br\n" +
"Accept-Language: zh-CN,zh;q=0.9,zh-TW;q=0.8\n" +
"Connection: keep-alive\n" +
"Host: " + urlObj.getHost() + "\n" +
"User-Agent: AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36\n\n";
String body = "";
channel.writeAndFlush(requestLine + header + body);
String result = resultHandler.getResultWithBlocking();
stop(group);
return result;
}
public static void main(String[] args) throws Exception {
HttpClientDemo demo = new HttpClientDemo();
System.out.println("运行结果:\n" + demo.get("http://www.12306.cn/"));
}
}
2.接收入站消息
package org.attempt.netty4.demo002;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
public class HttpClientHandler extends SimpleChannelInboundHandler {
private ResultHandler resultHandler;
public HttpClientHandler(ResultHandler resultHandler) {
this.resultHandler = resultHandler;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
resultHandler.setResult(msg.toString());
}
}
3.处理类
package org.attempt.netty4.demo002;
import io.netty.channel.EventLoopGroup;
import java.util.concurrent.atomic.AtomicReference;
public class ResultHandler {
private EventLoopGroup group;
private AtomicReference<String> result = new AtomicReference<>();
public ResultHandler() {
}
public ResultHandler(EventLoopGroup group) {
this.group = group;
}
public String getResultWithoutBlocking() {
if(null != result && null != group) {
group.shutdownGracefully();
}
return result.get();
}
public String getResultWithBlocking() {
while(null == result.get()) {
//循环等待
}
if(null != group) {
group.shutdownGracefully();
}
return result.get();
}
public String getResultWithBlocking(long timeout) {
long time = System.currentTimeMillis();
while(null == result.get()) {
if(System.currentTimeMillis() - time > timeout) {
break;
}
}
return result.get();
}
public void setResult(String resultStr) {
result.set(resultStr);
}
public void setGroup(EventLoopGroup group) {
this.group = group;
}
}
结果:
http://kyfw.12306.cn或https://kyfw.12306.cn时,重定向为https://kyfw.12306.cn/otn
var newUrl="";
//console.log("reg1:"+reg1.test(url_ky))
//console.log("reg2:"+reg2.test(url_ky))
if(reg1.test(url_ky))
{
newUrl=url_ky.replace(reg1,"https://kyfw.12306.cn/$1");
window.location=newUrl;
}else if(reg2.test(url_ky)){
newUrl=url_ky.replace(reg2,"https://kyfw.12306.cn/otn");
window.location=newUrl;
}else if(url=="www.12306.cn"||url=="www.95306.cn"){
window.location="/mormhweb/";
}else if(url=="kyfw.95306.cn"){
window.location="/otn/";
}
/*
if(url=="www.12306.cn")
{
window.location="/mormhweb/";
}
else
{
if(url=="wap.12306.cn")
{
window.location="/mormhwap/";
}
else
{
alert("非法的地址,浏览器将关闭!");
window.close();
}
}
*/
</script>
</html>