.NET开发从IE浏览器跳转至谷歌浏览器
前言
运用C#开发window窗体程序适用于从IE浏览器跳转至谷歌浏览器地址
一、窗体程序核心代码
1.跳转代码
代码如下(示例):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;
using System.Windows.Forms;
namespace openurl
{
partial class Form1
{
static Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //侦听socket
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
//隐藏窗体
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
SetVisibleCore(false);
//暴露Socket以方便浏览器访问
_socket.Bind(new IPEndPoint(IPAddress.Any, 31685));
_socket.Listen(1);
_socket.BeginAccept(new AsyncCallback(OnAccept), _socket); //开始接收来自浏览器的http请求(其实是socket连接请求)
Console.Read();
}
#endregion
static void OnAccept(IAsyncResult ar)
{
try
{
Socket socket = ar.AsyncState as Socket;
Socket new_client = socket.EndAccept(ar); //接收到来自浏览器的代理socket
//NO.1 并行处理http请求
socket.BeginAccept(new AsyncCallback(OnAccept), socket); //开始下一次http请求接收 (此行代码放在NO.2处时,就是串行处理http请求,前一次处理过程会阻塞下一次请求处理)
byte[] recv_buffer = new byte[1024 * 640];
int real_recv = new_client.Receive(recv_buffer); //接收浏览器的请求数据
string recv_request = Encoding.UTF8.GetString(recv_buffer, 0, real_recv);
Console.WriteLine(recv_request); //将请求显示到界面
if (!string.IsNullOrEmpty(recv_request.Trim()))
{
//处理请求字符串参数
string begin = "GET";
string end = "HTTP";
int IndexofBegin = recv_request.IndexOf(begin);
int IndexofEnd = recv_request.IndexOf(end);
string param = recv_request.Substring(IndexofBegin + 4, IndexofEnd - IndexofBegin - 4);
Resolve(recv_request, new_client, param); //解析、路由、处理
}
}
catch(Exception e)
{
Console.WriteLine("请求浏览器异常" + MessageBox.Show(e.ToString())); //将请求显示到界面
}
}
/// <summary>
/// 按照HTTP协议格式 解析浏览器发送的请求字符串
/// </summary>
/// <param name="request"></param>
/// <param name="response"></param>
static void Resolve(string request, Socket response, string recv_params)
{
//浏览器发送的请求字符串request格式类似这样:
//GET /index.html HTTP/1.1
//Host: 127.0.0.1:8081
//Connection: keep-alive
//Cache-Control: max-age=0
//
//id=123&pass=123 (post方式提交的表单数据,get方式提交数据直接在url中)
string[] strs = request.Split(new string[] { "\r\n" }, StringSplitOptions.None); //以“换行”作为切分标志
if (strs.Length > 0) //解析出请求路径、post传递的参数(get方式传递参数直接从url中解析)
{
string[] items = strs[0].Split(' '); //items[1]表示请求url中的路径部分(不含主机部分)
Dictionary<string, string> param = new Dictionary<string, string>();
if (strs.Contains("")) //包含空行 说明存在post数据
{
string post_data = strs[strs.Length - 1]; //最后一项
if (post_data != "")
{
string[] post_datas = post_data.Split('&');
foreach (string s in post_datas)
{
param.Add(s.Split('=')[0], s.Split('=')[1]);
}
}
}
Home.WmsPage(response);
Process myP = new Process();
string url = getApplicationByType("url");
url = url + recv_params;
string chrome = getApplicationByType("chrome");
if (!string.IsNullOrEmpty(url.Trim()))
{
if (string.IsNullOrEmpty(chrome.Trim()))
{
//进程默认方式打开谷歌浏览器
myP.StartInfo.FileName = "chrome.exe";
myP.StartInfo.Arguments = url + recv_params;
myP.Start();
}
else
{
//从配置文件打开谷歌浏览器
Process.Start(@chrome, url);
}
}
}
}
//1.从外部读取配置文件中跳转url地址 2.从配置文件中读取谷歌浏览器可执行文件路径地址
static string getApplicationByType(string type)
{
string result = "";
string[] lines = System.IO.File.ReadAllLines(@"C:\luckyun\application.txt");
foreach (string line in lines)
{
if (line.Contains("url") && type.Equals("url"))
{
result = line.Replace("url=", "");
break;
}
if (line.Contains("chrome") && type.Equals("chrome"))
{
result = line.Replace("chrome=","");
break;
}
}
return result;
}
}
#region 处理请求 并按照HTTP协议格式发送数据到浏览器
/// <summary>
/// 请求首页
/// </summary>
class Home
{
public static void WmsPage(Socket response)
{
string statusline = "HTTP/1.1 200 OK\r\n"; //状态行
byte[] statusline_to_bytes = Encoding.UTF8.GetBytes(statusline);
string content =
"<html>" +
//禁止浏览器调用默认favicon.ico页面
"<link rel=icon href=data:; base64,= >" +
"<head>" +
"<title>单点登录跳转页</title>" +
"</head>" +
"<body>" +
"<div style=\"text-align:center\">" +
"请在chrome浏览器打开wms系统" +
"</div>" +
"</body>" +
"</html>"; //内容
byte[] content_to_bytes = Encoding.UTF8.GetBytes(content);
string header = string.Format("Content-Type:text/html;charset=UTF-8\r\nContent-Length:{0}\r\n", content_to_bytes.Length);
byte[] header_to_bytes = Encoding.UTF8.GetBytes(header); //应答头
response.Send(statusline_to_bytes); //发送状态行
response.Send(header_to_bytes); //发送应答头
response.Send(new byte[] { (byte)'\r', (byte)'\n' }); //发送空行
response.Send(content_to_bytes); //发送正文(html)
response.Close();
}
}
#endregion
}