补充 宝玉 之《URL欺骗之以假乱真!》之 POST 方法提交数据 之 处理!

类别:Java 点击:0 评论:0 推荐:

补充 宝玉 之《URL欺骗之以假乱真!》之 POST 方法提交数据 之 处理!
(之乎者也,怪别扭的!)

我们首先搭建一个环境:
IIS 代理一下 Resin 下的 jsp 页面! (Resin 乃是 Java 应用服务器)

1.Resin 获取:
http://www.caucho.com/download/resin-2.1.16.zip
下载后解压某目录,如:
E:\Resin\resin-2.1.16\

2.配置 Resin  (Java SDK 的配置就不赘述)
用文本编辑器打开:
E:\Resin\resin-2.1.16\conf\resin.conf

<http port='8080'/>
可配置端口,resin 默认的是 8080 !
如果可用就不改!

<welcome-file-list>simplepost.jsp ,index.xtp, index.jsp, index.html </welcome-file-list>
可配置默认欢迎页面!

3.在 E:\Resin\resin-2.1.16\webapps\ 下创建新目录 test:
编写 E:\Resin\resin-2.1.16\webapps\test\index.jsp 并保存!
E:\Resin\resin-2.1.16\webapps\test\  就是一个 Application

<%@ page import='java.util.*'%>
<HTML>
<head>
<title>test</title>
</head>
<h1>Form Values:</h1>
<table>
<%
Enumeration e = request.getParameterNames();
while (e.hasMoreElements())
{
 String name = (String) e.nextElement();
 String[] values = (String[]) request.getParameterValues(name);
 %>
 <tr><td>
 <%= name %><td><%= values[0] %>
 <%
 if (values.length > 1)
 {
  for (int i = 1; i < values.length; i++)
  {
   %>,<%= values[i] %><%
  }
 }
}
%>
</table>
<form action='http://localhost' method='post'>
<input name='Comment' type="text" value="<%= request.getParameter("Comment") %>">
<input name='Comment2' type="text" value="<%= request.getParameter("Comment2") %>">
<input type=submit>
</form>
</body>
</HTML>


4.编写 C# Openlab.UrlCheat.cs : (修改宝玉的代码基础上完成POST操作的处理)

//Openlab.UrlCheat.cs
//命令行编译: csc /t:library Openlab.UrlCheat.cs
//生成的 Openlab.UrlCheat.dll 存放在 IIS 主目录下建一个 bin 目录!
//如: C:\Inetpub\wwwroot\bin\Openlab.UrlCheat.dll
namespace Openlab.UrlCheat
{
 using System;
 using System.Configuration;
 using System.Web;
 using System.IO;
 using System.Net;
 using System.Text;

 //原 Globals.cs
 /// <summary>
 /// Summary description for Globals.
 /// </summary>
 public class Globals
 {

  // 默认域名为博客堂
  private static string defaultDomain = "blog.joycode.com";

  public static bool IsNullorEmpty(string text)
  {
   if (text != null)
   {
    return (text.Trim() == string.Empty);
   }
   return true;
  }

  /// <summary>
  /// 根据Url返回HttpWebResponse对象
  /// </summary>
  /// <param name="url"></param>
  /// <returns></returns>
  public static HttpWebResponse WebResponse(string url)
  {
   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
   HttpWebResponse response = (HttpWebResponse)request.GetResponse();
   return response;
  }

  /// <summary>
  /// 获取网页的编码信息
  /// </summary>
  /// <param name="response"></param>
  /// <returns></returns>
  /// <remarks>如果是网页,则其ConentType中含有编码信息,如"text/html; charset=utf-8"</remarks>
  public static Encoding GetEncoding(HttpWebResponse response)
  {
   string name = response.ContentEncoding;
   Encoding code = Encoding.Default;
   if (name == "")
   {
    string contentType = response.ContentType;
    if (contentType.ToLower().IndexOf("charset") != -1)
    {
     name = contentType.Substring(contentType.ToLower().IndexOf("charset=") + "charset=".Length);
    }
   }

   if (name != "")
   {
    try
    {
     code = Encoding.GetEncoding(name);
    }
    catch{}
   }
   return code;
  }

  /// <summary>
  /// 获取文本内容
  /// </summary>
  /// <param name="response"></param>
  /// <returns></returns>
  public static string TextContent(HttpWebResponse response)
  {
   string buffer = "",line;

   Stream stream = response.GetResponseStream();
   StreamReader reader = new StreamReader(stream, GetEncoding(response));
  
   //buffer = "<base href=http://localhost:1080 />";
   while( (line = reader.ReadLine())!=null )
   {
   
    buffer += line + "\r\n";
   }
   stream.Close();

   return buffer;
  }

  //post Copy & paste from QuickStart by playyuer $ at $ Microshaoft.com
  //http://chs.gotdotnet.com/quickstart/util/srcview.aspx?path=/quickstart/howto/samples/net/WebRequests/clientPOST.src&file=CS\clientpost.cs&font=3
  //另外本人还有一篇老帖可参考
  // 《C# 写的 HttpRequsetResponse 类,异步、事件... 还热乎着呢!》
  // http://blog.csdn.net/playyuer/archive/2003/07/03/2856.aspx
  public static string getPage(string url,string payload)
  {
   System.Net.WebResponse result = null;
   string s = "";
   try
   {

    WebRequest req = WebRequest.Create(url);
    req.Method = "POST";
    req.ContentType = "application/x-www-form-urlencoded";
    StringBuilder UrlEncoded = new StringBuilder();
    Char[] reserved = {'?', '=', '&'};
    byte[] SomeBytes = null;

    if (payload != null)
    {
     int i=0, j;
     while(i<payload.Length)
     {
      j=payload.IndexOfAny(reserved, i);
      if (j==-1)
      {
       UrlEncoded.Append(HttpUtility.UrlEncode(payload.Substring(i, payload.Length-i)));
       break;
      }
      UrlEncoded.Append(HttpUtility.UrlEncode(payload.Substring(i, j-i)));
      UrlEncoded.Append(payload.Substring(j,1));
      i = j+1;
     }
     SomeBytes = Encoding.UTF8.GetBytes(UrlEncoded.ToString());
     req.ContentLength = SomeBytes.Length;
     Stream newStream = req.GetRequestStream();
     newStream.Write(SomeBytes, 0, SomeBytes.Length);
     newStream.Close();
    }
    else
    {
     req.ContentLength = 0;
    }

    result = req.GetResponse();
    Stream ReceiveStream = result.GetResponseStream();
    Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
    StreamReader sr = new StreamReader( ReceiveStream, encode );
    Console.WriteLine("\r\n已接收到响应流");
    Char[] read = new Char[256];
    int count = sr.Read( read, 0, 256 );
    Console.WriteLine("HTML...\r\n");
    while (count > 0)
    {
     String str = new String(read, 0, count);
     Console.Write(str);
     // add by playyuer
     s += str;
     count = sr.Read(read, 0, 256);
    }
    Console.WriteLine("");
    return s;
   }
   catch(Exception e)
   {
    Console.WriteLine( e.ToString());
    Console.WriteLine("\r\n找不到请求 URI,或者它的格式不正确");
    return s;
   }
   finally
   {
    if ( result != null )
    {
     result.Close();
    }
   
   }
  }


  /// <summary>
  /// 域名
  /// </summary>
  /// <remarks>如果支持泛域名解析,那么也可以做到1bu.com那样的效果:)</remarks>
  public static string Domain
  {
   get
   {
    string domain = ConfigurationSettings.AppSettings["Domain"];
    if (domain == null || domain == "")
     domain = defaultDomain;
    return domain;
   }
  }

  /// <summary>
  /// 域名的URL
  /// </summary>
  public static string DomainUrl
  {
   get
   {
    string url = Domain.ToLower();
    if (!url.StartsWith("http://"))
    {
     url = "http://" + url;
    }
    if (!url.EndsWith("/"))
    {
     url = url + "/";
    }
    return url;
   }
  }

  /// <summary>
  /// 真实地址
  /// </summary>
  /// <param name="rawUrl"></param>
  /// <returns></returns>
  public static string RealUrl(string rawUrl)
  {
   string realUrl;
   realUrl = Globals.DomainUrl + rawUrl.TrimStart('/');
   return realUrl;
  }

  static public string ApplicationPath
  {

   get
   {
    string applicationPath = HttpContext.Current.Request.ApplicationPath;

    if (applicationPath == "/")
    {
     return string.Empty;
    }
    else
    {
     return applicationPath.ToLower();
    }
   }
  }
 }

 //原 Redirect.cs
 /// <summary>
 /// 转向URL
 /// </summary>
 public class Redirect : IHttpHandler
 {
  public Redirect()
  {
   
  }

  public void ProcessRequest(HttpContext context)
  {
   string rawUrl = context.Request.RawUrl.ToLower();
   string realUrl = rawUrl;
   if (!Globals.IsNullorEmpty(rawUrl))
   {
    if (!rawUrl.StartsWith("http://"))
    {
     realUrl = Globals.RealUrl(rawUrl);
    }
   }
   context.Response.Redirect(realUrl);
   context.Response.End();
  }


  // Properties
  public bool IsReusable
  {
   get
   {
    return false;
   }
  }
 }

 //原 WebResponse.cs
 /// <summary>
 /// 输出内容
 /// </summary>
 public class WebResponse : IHttpHandler
 {
  
  public void ProcessRequest(HttpContext context)
  {
   string rawUrl = context.Request.RawUrl.ToLower();
   if (!Globals.IsNullorEmpty(rawUrl))
   {
    // 如果是"http://"开头则表示是绝对路径,直接跳转即可
    if (!rawUrl.StartsWith("http://"))
    {
     string realUrl = Globals.RealUrl(rawUrl);
     //add by playyuer $ at $ Microshaoft.com
     if (context.Request.HttpMethod.ToLower() == "get")
     {
      HttpWebResponse response = Globals.WebResponse(realUrl);

      // 如果不是文本类型的,就跳转
      if (!response.ContentType.ToLower().StartsWith("text/"))
       context.Response.Redirect(realUrl);

      // 文本类型则先获取文本内容,然后直接输出到浏览.
      string content = Globals.TextContent(response);
      context.Response.Write(content);
     }
      //add by playyuer $ at $ Microshaoft.com
     else //post
     {
      string S = "";
      foreach (string s in context.Request.Form.AllKeys)
      {
       if (S.Length > 0)
        S += "&";
       S += s + "=" + context.Request.Form[s];
      }
      //context.Response.Write(S);
      context.Response.Write(Globals.getPage(realUrl,S));
     }
    }
    else
    {
     context.Response.Redirect(rawUrl);
    }
   }
   else
   {
    //
   }
   context.Response.End();
  }

  public bool IsReusable
  {
   get
   {
    return false;
   }
  }
 }
}


4.IIS 主目录下的 web.Config ,如: C:\Inetpub\wwwroot\web.Config :

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <system.web>
  <compilation defaultLanguage="c#" debug="true" />
  <httpHandlers>
   <add verb="*" path="*.gif" type="Openlab.UrlCheat.Redirect, Openlab.UrlCheat" />
   <add verb="*" path="*.jpg" type="Openlab.UrlCheat.Redirect, Openlab.UrlCheat" />
   <add verb="*" path="*.jpeg" type="Openlab.UrlCheat.Redirect, Openlab.UrlCheat" />
   <add verb="*" path="*.rar" type="Openlab.UrlCheat.Redirect, Openlab.UrlCheat" />
   <add verb="*" path="*.zip" type="Openlab.UrlCheat.Redirect, Openlab.UrlCheat" />
   <add verb="*" path="*.webinfo" type="System.Web.HttpForbiddenHandler"/>
   <add verb="GET" path="*" type="Openlab.UrlCheat.WebResponse, Openlab.UrlCheat" />
   <add verb="POST" path="*" type="Openlab.UrlCheat.WebResponse, Openlab.UrlCheat" />
  </httpHandlers>
 </system.web>
 <appSettings>
  <!-- 您可以修改这个域名 -->
  <add key="Domain" value="http://localhost:8080/test/" />
 </appSettings>
</configuration>


5.运行 Resin 及 IIS
E:\Resin\resin-2.1.16\bin\httpd.exe

6.在 IE 地址栏访问: http://localhost
提交一些数据测试!看看回显是否正确?!

我测的够慢的!
另外宝玉和我都没考虑替换 href  的 url 处理!

本文地址:http://com.8s8s.com/it/it11201.htm