Fiddler在HTTP编程过程是不可多得的利器,特别是它使用的是代理方式,能够提供非侵入式的HTTP通信报文编程,在Web接口调试方面很方便。特别是它提供使用JScript .NET方式进行功能拓展,让Web前端调试编程变得很容易
先科普
Fiddler, The free web debugging proxy for any browser, system or platform
百度百科的介绍
Fiddler 是用C#写出来的,它包含一个简单却功能强大的基于JScript .NET 事件脚本子系统,它的灵活性非常棒,可以支持众多的http调试任务,并且能够使用.net框架语言进行扩展。
Fiddler官方地址
http://www.telerik.com/fiddler
最近有一个简单的需求,就是使用Fidder把去向特定IP和URL的HTTP请求标注起来,并且保存到指定文件中去。下面是实现的FiddlerScript脚本,供参考
1. 筛选指定条件的请求,在发起前拦截
static function OnBeforeRequest(oSession: Session) {
// 筛选指定条件的请求
if (oSession.HostnameIs("118.145.4.46") &&
oSession.HTTPMethodIs("POST") &&
oSession.uriContains("/member/monitor/customerhold!sum.action")) {
oSession["ui-color"] = "red";
}
}
2.设置菜单栏接口开关
// 菜单栏名称
public static RulesOption("Automatically Dump Summary Data")
var m_AutoDumpSumData: boolean = false;
3.请求完成后,将数据包按时间格式指定文件名并保存
static function OnDone(oSession: Session) {
if (null == Session){
return;
}
// 筛选指定条件的请求
if(m_AutoDumpSumData){
if (oSession.HostnameIs("118.145.4.46") &&
oSession.HTTPMethodIs("POST")){
var dSessionId = oSession.id;
// 时间格式化
var date = new Date();
var month = date.getMonth() + 1;
var strDate = date.getDate();
var strHours = date.getHours();
var strMinutes = date.getMinutes();
var strSeconds = date.getSeconds();
var strMilliSeconds = date.getMilliseconds();
if (month >= 1 && month = 0 && strDate = 0 && strHours = 0 && strMinutes = 0 && strSeconds = 0 && strMilliSeconds = 10 && strMilliSeconds
完整的源代码
import System;
import System.Windows.Forms;
import Fiddler;
// INTRODUCTION
//
// Well, hello there!
//
// Don't be scared! :-)
//
// This is the FiddlerScript Rules file, which creates some of the menu commands and
// other features of Fiddler. You can edit this file to modify or add new commands.
//
// The original version of this file is named SampleRules.js and it is in the
// \Program Files\Fiddler\ folder. When Fiddler first runs, it creates a copy named
// CustomRules.js inside your \Documents\Fiddler2\Scripts folder. If you make a
// mistake in editing this file, simply delete the CustomRules.js file and restart
// Fiddler. A fresh copy of the default rules will be created from the original
// sample rules file.
// The best way to edit this file is to install the FiddlerScript Editor, part of
// the free SyntaxEditing addons. Get it here: http://fiddler2.com/r/?SYNTAXVIEWINSTALL
// GLOBALIZATION NOTE: Save this file using UTF-8 Encoding.
// JScript.NET Reference
// http://fiddler2.com/r/?msdnjsnet
//
// FiddlerScript Reference
// http://fiddler2.com/r/?fiddlerscriptcookbook
class Handlers
{
// *****************
//
// This is the Handlers class. Pretty much everything you ever add to FiddlerScript
// belongs right inside here, or inside one of the already-existing functions below.
//
// *****************
// The following snippet demonstrates a custom-bound column for the Web Sessions list.
// See http://fiddler2.com/r/?fiddlercolumns for more info
/*
public static BindUIColumn("Method", 60)
function FillMethodColumn(oS: Session): String {
return oS.RequestMethod;
}
*/
// The following snippet demonstrates how to create a custom tab that shows simple text
/*
public BindUITab("Flags")
static function FlagsReport(arrSess: Session[]):String {
var oSB: System.Text.StringBuilder = new System.Text.StringBuilder();
for (var i:int = 0; i-1)) { // Case sensitive
oSession.url = oSession.url.Replace(gs_ReplaceToken, gs_ReplaceTokenWith);
}
if ((null != gs_OverridenHost) && (oSession.host.toLowerCase() == gs_OverridenHost)) {
oSession["x-overridehost"] = gs_OverrideHostWith;
}
if ((null!=bpRequestURI) && oSession.uriContains(bpRequestURI)) {
oSession["x-breakrequest"]="uri";
}
if ((null!=bpMethod) && (oSession.HTTPMethodIs(bpMethod))) {
oSession["x-breakrequest"]="method";
}
if ((null!=uiBoldURI) && oSession.uriContains(uiBoldURI)) {
oSession["ui-bold"]="QuickExec";
}
if (m_SimulateModem) {
// Delay sends by 300ms per KB uploaded.
oSession["request-trickle-delay"] = "300";
// Delay receives by 150ms per KB downloaded.
oSession["response-trickle-delay"] = "150";
}
if (m_DisableCaching) {
oSession.oRequest.headers.Remove("If-None-Match");
oSession.oRequest.headers.Remove("If-Modified-Since");
oSession.oRequest["Pragma"] = "no-cache";
}
// User-Agent Overrides
if (null != sUA) {
oSession.oRequest["User-Agent"] = sUA;
}
if (m_Japanese) {
oSession.oRequest["Accept-Language"] = "ja";
}
if (m_AutoAuth) {
// Automatically respond to any authentication challenges using the
// current Fiddler user's credentials. You can change (default)
// to a domain\\username:password string if preferred.
//
// WARNING: This setting poses a security risk if remote
// connections are permitted!
oSession["X-AutoAuth"] = "(default)";
}
if (m_AlwaysFresh && (oSession.oRequest.headers.Exists("If-Modified-Since") || oSession.oRequest.headers.Exists("If-None-Match")))
{
oSession.utilCreateResponseAndBypassServer();
oSession.responseCode = 304;
oSession["ui-backcolor"] = "Lavender";
}
}
// This function is called immediately after a set of request headers has
// been read from the client. This is typically too early to do much useful
// work, since the body hasn't yet been read, but sometimes it may be useful.
//
// For instance, see
// http://blogs.msdn.com/b/fiddler/archive/2011/11/05/http-expect-continue-delays-transmitting-post-bodies-by-up-to-350-milliseconds.aspx
// for one useful thing you can do with this handler.
//
// Note: oSession.requestBodyBytes is not available within this function!
/*
static function OnPeekAtRequestHeaders(oSession: Session) {
var sProc = ("" + oSession["x-ProcessInfo"]).ToLower();
if (!sProc.StartsWith("mylowercaseappname")) oSession["ui-hide"] = "NotMyApp";
}
*/
//
// If a given session has response streaming enabled, then the OnBeforeResponse function
// is actually called AFTER the response was returned to the client.
//
// In contrast, this OnPeekAtResponseHeaders function is called before the response headers are
// sent to the client (and before the body is read from the server). Hence this is an opportune time
// to disable streaming (oSession.bBufferResponse = true) if there is something in the response headers
// which suggests that tampering with the response body is necessary.
//
// Note: oSession.responseBodyBytes is not available within this function!
//
static function OnPeekAtResponseHeaders(oSession: Session) {
//FiddlerApplication.Log.LogFormat("Session {0}: Response header peek shows status is {1}", oSession.id, oSession.responseCode);
if (m_DisableCaching) {
oSession.oResponse.headers.Remove("Expires");
oSession.oResponse["Cache-Control"] = "no-cache";
}
if ((bpStatus>0) && (oSession.responseCode == bpStatus)) {
oSession["x-breakresponse"]="status";
oSession.bBufferResponse = true;
}
if ((null!=bpResponseURI) && oSession.uriContains(bpResponseURI)) {
oSession["x-breakresponse"]="uri";
oSession.bBufferResponse = true;
}
}
static function OnBeforeResponse(oSession: Session) {
if (m_Hide304s && oSession.responseCode == 304) {
oSession["ui-hide"] = "true";
}
}
/*
// This function executes just before Fiddler returns an error that it has
// itself generated (e.g. "DNS Lookup failure") to the client application.
// These responses will not run through the OnBeforeResponse function above.
static function OnReturningError(oSession: Session) {
}
*/
/*
// This function executes after Fiddler finishes processing a Session, regardless
// of whether it succeeded or failed. Note that this typically runs AFTER the last
// update of the Web Sessions UI listitem, so you must manually refresh the Session's
// UI if you intend to change it.
*/
static function OnDone(oSession: Session) {
if (null == Session){
return;
}
// if AutoDumpSumData option is open
if(m_AutoDumpSumData){
if (oSession.HostnameIs("118.145.4.46") &&
oSession.HTTPMethodIs("POST")){
var dSessionId = oSession.id;
var date = new Date();
var month = date.getMonth() + 1;
var strDate = date.getDate();
var strHours = date.getHours();
var strMinutes = date.getMinutes();
var strSeconds = date.getSeconds();
var strMilliSeconds = date.getMilliseconds();
if (month >= 1 && month = 0 && strDate = 0 && strHours = 0 && strMinutes = 0 && strSeconds = 0 && strMilliSeconds = 10 && strMilliSeconds
参考
http://my.oschina.net/leejun2005/blog/399108