Skip to content
Jack Chen edited this page Jan 22, 2014 · 5 revisions
  • Welcome to the diddler wiki!
Fiddler是一个非常强大的http(s)协议分析工具,如果你不知道它是什么,可以自行google一下,简单的说它可以代替Chrome开发人员工具中Network面板或Firefox的HttpWatch插件的功能。
  • Diddler是什么呢?

就是手机端的具备Fiddler,Chrome开发人员工具中Network面板,或Firefox的HttpWatch插件的功能。功能具备,界面简洁:







package universsky.diddler;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

/**
 * @author 东海陈光剑
 * 2014年1月21日  下午5:34:27
 */
public class ItemActivity extends Activity{
        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.item);
                TextView itemTextView = (TextView) findViewById(R.id.itemView1);
                TextView urlTextView = (TextView) findViewById(R.id.urlView);
                
                //Retrieves a map of extended data from the intent.
                Bundle bundle = getIntent().getExtras();
                
                //Returns the value associated with the given key,
                //or null if no mapping of the desired type exists for the given key 
                //or a null value is explicitly associated with the key
                CharSequence item = bundle.getCharSequence("item");//读出数据
                //Open Declaration void android.widget.TextView.setText(CharSequence text)
                itemTextView.setText(item);
                //itemTextView.append(item);
                
                String path = "";
                String host = "";
                String url = "http://";
                String itemStr = item.toString();
                
                Matcher m1 = Pattern.compile("GET\\s(.*)\\sHTTP/1.1").matcher(itemStr);
                
                if (m1.find()){
                        path = itemStr.substring(m1.start(),m1.end());
                        path = path.substring( path.indexOf("GET") + 4, path.indexOf("HTTP/1.1")-1);
                }
                
                Matcher m2 = Pattern.compile("Host:\\s(.*)").matcher(itemStr);
                if (m2.find()){
                        host = itemStr.substring(m2.start(),m2.end());
                        host = host.substring( host.indexOf("Host:") + 5);
                }
                
                url += host + path;
                url = url.replaceAll("\\s*|\t|\r|\n", "");
                urlTextView.setText(url);                
                
        }

}

 /////////////////////////////////////////////////////////////////////////////

        /**
         * This runnable is used for refreshing the TCPdump's process standard
         * output.
         */
        private Runnable updateOutputText = new Runnable() {
                public void run() {
                        try {
                                // 打开tcpdump资源文件
                                mContext.getResources().openRawResource(R.raw.tcpdump);
                                // 获取tcpdump命令执行的结果
                                if ((tcpdump.getInputStream().available() > 0) == true) {
                                        byte[] buffer = new byte[bufferSize];
                                        //String getPath = "";
                                        //String hostName = "";
                                        //String buffer = "";
                                        try {
                                                // 把tcpdump命令执行的结果的 “输出流” 赋值给字节数组buffer
                                                //int java.io.DataInputStream.read(byte[] buffer, int offset, int length) throws IOException
                                                tcpdump.getInputStream().read(buffer, 0, bufferSize);
                                                //逐行读字节流
                                                
                                                //buffer = tcpdump.getInputStream().readLine();
                                                // Clears the screen if it's full.
//                                                if (outputText.length() + buffer.length() >= MaxSize)
//                                                        outputText.setText("");
                                                
                                                
                                                /**
                                                if (outputText.length() + buffer.length >= MaxSize)
                                                        outputText.setText("");
                                                */
                                                
                                                // 防止无限加载,导致内存溢出
                                                
                                                if ( itemList.size() > MAX_COUNT ) {
                                                        // 把itemList置空
                                                        itemList.clear();        
                                                        itemList2.clear();
                                                }
                                                
                                                
                                        } catch (IOException e) {
                                                stopRefreshing();
                                                return;
                                        }
                                        String bufferStr = new String(buffer);
                                        
                                        /**
                                         * @author chenguangjian
                                         *                    2014.1.8
                                         * 正则匹配出需要的数据包段
                                         */
                                        
                                        String pStr = "GET\\s+[\\x00-\\x7F]*\\nHost:[\\x00-\\x7F]*\\n\\n";
//                                        String pStr = "GET\\s+[\\x00-\\x7F]*";
                                        Pattern p = Pattern.compile(pStr);
                                        Matcher m0 = p.matcher(bufferStr);
//                                        String mStr = "";
                                        while(m0.find()){
                                                String item = "";
                                                int s = m0.start();
                                                int e = m0.end();
                                                item = bufferStr.substring(s, e);
                                                itemList.add(item);
//                                                mStr += "\n[" + countPackets + "]" + 
//                                                                bufferStr.substring(s, e);
                                                countPackets++;
                                        }
                                        
                                        //outputText.append(mStr);
                                        
                                        final ArrayList<HashMap<String,Object>> listItem = new ArrayList<HashMap<String,Object>>();
                                        final ArrayList<HashMap<String,Object>> listItem2 = new ArrayList<HashMap<String,Object>>();
                                        for(int i = 0; i < itemList.size(); i++){
                                                HashMap<String,Object> map = new HashMap<String,Object>();
                                                java.text.DateFormat fmt = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                                                String s =  fmt.format(new Date());
                                                map.put("item_title", "[ " + s + "]" + "第" + i + "个HTTP请求:  " );
                                                
                                                //获取GET path
                                                String item = itemList.get(i);
                                                map.put("item_text0", item);
                                                listItem2.add(map);
                                                String request = "";
                                                Matcher m1 = Pattern.compile("GET\\s(.*)\\sHTTP/1.1").matcher(item);
                                                if (m1.find()){
                                                        request = item.substring(m1.start(),m1.end());                                                
                                                        map.put("item_text", request);
                                                        listItem.add(map);
                                                }
                                        }
                                        //生成适配器的Item和动态数组对应的元素
                                        /**
                                         * android.widget.SimpleAdapter.SimpleAdapter(
                                         * Context context, 
                                         * List<? extends Map<String, ?>> data, 
                                         * int resource, 
                                         * String[] from, 
                                         * int[] to
                                         * )
                                         */
                                        android.widget.SimpleAdapter listItemAdapter = new android.widget.SimpleAdapter(
                                                        mContext,             // Context
                                                        listItem,        // List
                                                        R.layout.list_items, // int resource 
                                                        new String[]{"item_title","item_text"}, // String[] from 
                                                        new int[]{R.id.ItemTitle,R.id.ItemText} // int[] to
                                                        );
                                        //Sets the data behind this ListView. 
                                        list.setAdapter(listItemAdapter);
                                        
                                         //添加点击  
                                list.setOnItemClickListener(new OnItemClickListener(){
                                                @Override
                                                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                                                long arg3) {
                                                        CharSequence item = (CharSequence) listItem2.get(arg2).get("item_text0");
                                                        //Open Declaration Toast android.widget.Toast.makeText(Context context, CharSequence text, int duration)
                                                        
                                                        //Toast.makeText(mContext, item, Toast.LENGTH_LONG).show();
                                                        
                                                        Intent intent=new Intent();
                                                        intent.setClass( activity, ItemActivity.class );
                                                        Bundle mBundle=new Bundle();
                                                        /*
                                                         * Inserts a CharSequence value into the mapping of this Bundle, replacing any existing value for the given key. Either key or value may be null.
                                                         */
                                                        mBundle.putCharSequence("item",  item);
                                                        intent.putExtras(mBundle);
                                                        mContext.startActivity(intent);
                                                }
                                                 
                                 });
                                        
                                        
                                        
                                }
                        } catch (IOException e) {
                                stopRefreshing();
                                return;
                        }
                        isHandler.postDelayed(updateOutputText, refreshRate);
                }
        };

        
        public TCPdumpHandler(TCPdump tcpdump, Context mContext, Activity activity,
                        boolean notificationEnabled) {

                this.activity = activity;
                // Acessing the app's settings.
                settings = mContext.getSharedPreferences(GlobalConstants.prefsName, 0);

                this.tcpdump = tcpdump;
                isHandler = new Handler();

                this.params = (EditText) activity.findViewById(paramsId);
                //this.outputText = (TextView) activity.findViewById(outputId);
                //this.scroller = (View) activity.findViewById(scrollerId);
                this.list = (ListView)activity.findViewById(R.id.listView1);
                this.pbar = (ProgressBar) activity.findViewById(pbarId);

                this.mContext = mContext;
                this.notificationEnabled = notificationEnabled;

                if (notificationEnabled) {
                        // Asociating the System's notification service with the
                        // notification manager.
                        nManager = (NotificationManager) mContext
                                        .getSystemService(Context.NOTIFICATION_SERVICE);

                        // Defining a notification that will be displayed when TCPdump
                        // starts.
                        notification = new Notification(R.drawable.icon,
                                        mContext.getString(R.string.tcpdump_notification),
                                        System.currentTimeMillis());
                        notification.setLatestEventInfo(mContext, "diddler", mContext
                                        .getString(R.string.tcpdump_notification_msg),
                                        PendingIntent.getActivity(mContext, 0, new Intent(mContext,
                                                        Main.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                                                        | Intent.FLAG_ACTIVITY_SINGLE_TOP),
                                                        PendingIntent.FLAG_CANCEL_CURRENT));
                        notification.flags |= Notification.FLAG_ONGOING_EVENT;
                }
        }

        /**
         * Starts a TCPdump process, enables refreshing and posts a notification.
         * 
         * @param params
         *            The parameters that TCPdump will use. For example: -i
         *            [interface name] -s [snaplen size] -w [filename]
         * 
         * @return 0 Everything went OK.<br>
         *         -1 TCPdump is already running.<br>
         *         -2 The device isn't rooted.<br>
         *         -4 Error when running the TCPdump command.<br>
         *         -5 Error when flushing the DataOutputStream.
         */
        
        public int start(String params) {
                
                int TCPdumpReturn;
                
                if ((TCPdumpReturn = tcpdump.start(params)) == 0) {
                        // if save to file, the outputText show  
                        if (settings.getBoolean("saveCheckbox", false) == true) {
                        } else {//if not save to file, show on the scroll view
                                startRefreshing();
                        }
                        
                        setProgressbarVisible();
                        if (notificationEnabled)
                                postNotification();
                        return 0;
                } else
                        return TCPdumpReturn;
        }

Clone this wiki locally