C#和java和android中的NetWorkAdapter,httpRequest,WebView,json,xml

原文地址:http://blog.csdn.net/intbird

C#NetWorkAdapter 20121011.=============================================================

        /// <summary>

        /// 显示网卡信息
        /// </summary>
        private void ShowAdapterInfo()
        {
            //获取主机上全部的网络适配器对象
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();


            AppendRtbText(string.Format("网适配器个数:{0}", adapters.Length));


            for (int i = 0; i < adapters.Length; i++)
            {
                AppendRtbText(string.Format("-----------------------------第{0}个网络适配器信息----------------------------- ", i + 1));
                AppendRtbText(string.Format("描写叙述信息:{0}", adapters[i].Description));
                AppendRtbText(string.Format("名称:{0}", adapters[i].Name));
                AppendRtbText(string.Format("类型:{0}", adapters[i].NetworkInterfaceType));
                AppendRtbText(string.Format("速度:{0}M", adapters[i].Speed / 1000 / 1000));
                AppendRtbText(string.Format("MAC地址:{0}", BitConverter.ToString(adapters[i].GetPhysicalAddress().GetAddressBytes())));


                //获取该网络适配器的配置对象
                IPInterfaceProperties adapterProperties = adapters[i].GetIPProperties();
                //获取并显示该网络适配器DNSserverIP地址信息
                IPAddressCollection dnsServers = adapterProperties.DnsAddresses;


                if (dnsServers.Count > 0)
                {
                    foreach (IPAddress dns in dnsServers)
                    {
                        AppendRtbText(string.Format("DNSserverIP地址:{0}", dns));
                    }
                }
                else
                {
                    AppendRtbText("DNSserverIP地址: \n");
                }


                AppendRtbText("\n");
            }
        }


        /// <summary>
        /// 向富文本框添追加文本
        /// </summary>
        /// <param name="rtb"></param>
        /// <param name="text"></param>
        public void AppendRtbText(string text)
        {
            this.rtb_AdappterInfo.AppendText(text + "\n");
        }

    }

java========================================

package com.xudeyu.tcpip;


import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;


/**
 * Tcp ip connection test
 * 
 * @author intbird@163.com time 2013-04-11
 * 
 */
public class NetWorkInterfaceTest
{


/**
* @param args
*/
public static void main(String[] args)
{


try
{
Enumeration<NetworkInterface> interfaceList = NetworkInterface
.getNetworkInterfaces();
if (interfaceList == null) System.out.print("No interface found");
else
{


while (interfaceList.hasMoreElements())
{
NetworkInterface netFace = interfaceList.nextElement();
System.out.println("Interface: " + netFace.getName());
System.out.println("description"+netFace.getDisplayName());
Enumeration<InetAddress> addressList = netFace
.getInetAddresses();


if (!addressList.hasMoreElements()) System.out
.println("no address for this interface!");
while (addressList.hasMoreElements())
{
InetAddress address = addressList.nextElement();
System.out.println("address:"
+ address.getHostAddress());

}
}
}


}
catch (SocketException e)
{
// TODO 自己主动生成的 catch 块
e.printStackTrace();
}


}


}


C#====================httpRequest

HttpRequest 和 httpResponse,asp.net中的也差不错

java===================httpRequest

package com.xudeyu.url;


import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;


public class URLConnectionTest
{


public void main(String[] args)
{
try
{
String urlName;
if (args.length > 0) urlName = args[0];
else urlName = "http://localhost";


URL url = new URL(urlName);
URLConnection connection = url.openConnection();


if (args.length > 2)
{
String username = args[0];
String password = args[1];


String input = username + " :" + password;
String encoding = base64Ecode(input);
connection.setRequestProperty("aAUthotization", "Basic"
+ encoding);


}
connection.connect();


Map<String, List<String>> headers = connection.getHeaderFields();
for (Entry<String, List<String>> entry : headers.entrySet())
{
String key = entry.getKey();
for (String value : entry.getValue())
{
System.out.print(key + " " + value);
}
}


System.out.print("getContentType" + connection.getContentType());
Scanner in = new Scanner(connection.getInputStream());
for (int n = 1; in.hasNext() && n <= 10; n++)
{
System.out.print(in.nextLine());
}


}
catch (Exception e)
{


}
}


private String base64Ecode(String input)
{
// TODO 自己主动生成的方法存根
return null;
}


}

C#webView


java webView看书上第七章,类似

java和C#的json不用多说

java xml

package com.xudeyu.xml;


import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;


import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.SwingWorker;
import javax.swing.event.TreeModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;


import org.w3c.dom.CharacterData;
import org.w3c.dom.*;  


public class DOMTreeTest {


public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
DOMTreeFrame frame=new DOMTreeFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}


}


class DOMTreeFrame extends JFrame {

private DocumentBuilder builder;


public DOMTreeFrame() {
setTitle("DOMTree");
setSize(500, 400);
setLocationByPlatform(true);


JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");

//打开文件
JMenuItem open=new JMenuItem("Open");
open.addActionListener(new ActionListener ()
{
@Override
public void actionPerformed(ActionEvent e) {
openFile();
}
});

//关闭窗口
JMenuItem  exit=new JMenuItem("Exit");
exit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});

//加入菜单
menu.add(open);
menu.add(exit);

menuBar.add(menu);
setJMenuBar(menuBar);



}

/**
* 选择一个xml文件
*/
public void openFile()
{
JFileChooser fileChooser=new JFileChooser();
fileChooser.setCurrentDirectory(new File("."));
fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter()
{
@Override
public boolean accept(File pathname)
{
return pathname.isDirectory()||pathname.getName().toLowerCase().endsWith(".xml");
}


@Override
public String getDescription()
{
return "chooser a xml file";
}
});

int r=fileChooser.showOpenDialog(this);
if(r!=JFileChooser.APPROVE_OPTION)
{
return ;
}

final File file=fileChooser.getSelectedFile();

new SwingWorker<Document,Void>()
{
@Override
protected Document doInBackground() throws Exception {

if(builder==null)
{
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
builder=factory.newDocumentBuilder();
}
return builder.parse(file);
}

protected void done()
{
try
{
Document doc =get();
JTree tree =new JTree(new DOMTreeModel(doc));

tree.setCellRenderer(new DOMTreeRenderer());
setContentPane(new JScrollPane(tree));
validate();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}.execute();

}


}


class DOMTreeModel implements TreeModel
{


private Document doc;
public DOMTreeModel (Document doc)
{
this.doc=doc;
}

@Override
public Object getRoot() {

return doc.getDocumentElement();
}


@Override
public Object getChild(Object parent, int index) {
Node node=(Node)parent;
NodeList list=node.getChildNodes();
return list.item(index);
}


@Override
public int getChildCount(Object parent) {
Node node=(Node)parent;
NodeList list=node.getChildNodes();
return list.getLength();
}


@Override
public boolean isLeaf(Object node) {

return getChildCount(node)==0;
}


@Override
public void valueForPathChanged(TreePath path, Object newValue) {

}


@Override
public int getIndexOfChild(Object parent, Object child) {
Node node=(Node)parent;
NodeList list=node.getChildNodes();

for(int i=0;i<list.getLength();i++)
{
if(getChild(node, i)==(child))
return i;
}
return -1;
}


@Override
public void addTreeModelListener(TreeModelListener l) {
}


@Override
public void removeTreeModelListener(TreeModelListener l) {

}
}


class DOMTreeRenderer extends DefaultTreeCellRenderer
{
public Component getTreeCellTendererComponnte(JTree tree
,Object value
,boolean selected
,boolean expanded
,boolean leaf
,int row
,boolean hasFocus)
{
Node node=(Node)value;

if( node instanceof Element )
return  elementPanel((Element)node);

super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);

if(node instanceof CharacterData)
setText(charaterString(((CharacterData)node)));
else
setText(node.getClass()+": "+node.toString());
return this;
}

public static JPanel elementPanel(Element e)
{
JPanel panel=new JPanel();
panel.add(new Label("Element: "+e.getTagName()));

final NamedNodeMap map=e.getAttributes();
panel.add(new JTable(new AbstractTableModel()
{


@Override
public int getRowCount() {

return map.getLength() ;
}


@Override
public int getColumnCount() {
return 2;

}


@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return columnIndex==0?map.item(rowIndex).getNodeName():map.item(rowIndex).getNodeValue();
}

}));
return panel;

}

public static String charaterString(CharacterData node)
{
StringBuilder builder=new StringBuilder(node.getData());
for(int i=0;i<builder.length();i++)
{
if(builder.charAt(i)=='\r')
{
builder.replace(i, i+1, "\\r");
i++;
}
else if(builder.charAt(i)=='\n')
{
builder.replace(i, i+1, "\\n");
i++;
}
else if(builder.charAt(i)=='\t')
{
builder.replace(i, i+1, "\\t");
i++;
}
}
if(node instanceof CDATASection)
builder.insert(0, "CDTASetion: ");
else if(node instanceof Text)
builder.insert(0, "Text: ");
else if(node instanceof Comment)
builder.insert(0, "Comment: ");

return builder.toString();
}

}

android===============================

Gson;

posted @ 2016-03-16 16:00  zfyouxi  阅读(341)  评论(0编辑  收藏  举报