现在的位置: 首页 > 综合 > 正文

网络编程(1)–Java的基本网络支持

2018年04月06日 ⁄ 综合 ⁄ 共 5461字 ⁄ 字号 评论关闭

1. 测试InetAddress的简单用法

public class InetAddressTest

{

  public static void main(String[] args) throws Exception

  {

      InetAddress   ip = InetAddress.getByName("www.crazyit.org");

     //IP字符串      

      System.out.println(ip.getHostAddress);

      InetAddress local = InetAddress.getByAddress(new byte[] (127.0.0.1));

      System.out.println("本机是否可达"+local.isReachable(5000));

      //全限定域名

     System.out.println(local.getCanonicalHostName());

    

  }

  

}


2. 使用URLDecoder 和URLEncoder

    public class URLDecoderTest

   {

     public static void main(String[] args) throws Exception

     {

       String keyWord = URLDecoder.decode("%E6%9D","UTF-8");

       System.out.println(keyWord);

       String urlStr = URLEncoder.encode("ROR敏捷开发最佳指南","GBK");

      System.out.println(urlStr);

      }

   }

3 使用URL 和URLConnection

    URL对象提供的openStream()可以读取该URL资源的InputStream,

    通过该方法可以非常方便地读取远程资源---甚至实现多线程下载

    class DownThread extends Thread

   {

      private final int BUFF_LEN = 32;

      private long start;

      private  long end;

      private InputStream is;

      private RandomAccessFile  raf;

      public DownThread(long start,long end,InputStream is,RandomAccessFile raf)

     {

       System.out.println(start+"------->"+end);

       this.start  = start;

       this.end = end;

       this.is = is;

       this.raf = raf;

      }

      public void run()

      {

         try

          {

            is.skip(start);

            raf.seek(start);

            byte[]    buff = new byte[BUFF_LEN];

            long contentLen =end-start;

            long times = contentLen/BUFF_LEN + 4;

            int hasRead = 0;

            for(int i=0;i<times;i++)

            {

               hasRead = is.read(buff);

                if(hasRead < 0)

               {

                    break;

               }

               raf.write(buff,0,hasRead);

            }

            }

             catch(Exception ex)

            {

                ex.printStackTrace();

            }

             finally

            {

             try

             {

                if(is != null)

                {           

                   is.close();

                }

               if(raf != null)

               {

                  raf.close();

               }

             }

            catch(Exception ex)

            {

               ex.printStackTrace();

           }

            }

            

      }

   }

   public class MutilDown

  {

       public static void main(String[] args)

       {

           final int DOWN_THREAD_NUM = 4;

           final String OUT_FILE_NAME = "down.jpg";

           InputStream[] isArr = new InputStream[DOWN_THREAD_NUM];

           RandomAccessFile[] outArr = new RandomAccessFile[DOWN_THREAD_NUM];

           try

           {

            URL  url = new URL("http://images.china-pub.com/shupi.jpg");

            isArr[0] = url.openStream();

            long fileLen = getFileLength(url);

           System.out.println("网络资源的大小"+fileLen);

           outArr[0] = new RandomAccessFile(OUT_FILE_NAME,"rw");

           for(int i=0;i<fileLen;i++)

           {

               outArr[0].write(0);

           }

            long numPerThred = fileLen/DOWN_THREAD_NUM;

            long left = fileLen % DOWN_THREAD_NUM;

            for(int i=0;i<DOWN_THREAD_NUM;i++)

            {

              if(i !=0)

              {

                isArr[i] = url.openStream();

                outArr[i] = new RandomAccessFile(OUT_FILE_NAME,"rw");

               }

              if(i = DOWN_THREAD_NUM-1)

              {

                 new DownThread(i*numPerThred,(i+1)*numPerThred+left,isArr[i],outArr[i]).start();

              }

             else

            {

                 new DownThread(i*numPerThred,(i+1)*numPerThred,isArr[i],outArr[i]).start();

            }

            }

 

           }

      catch(Exception ex)

      {

         ex.printStackTrace();

      }

       }

   public static long getFileLength(URL url) throws Exception

   {

     long length=0;

     URLConnection con = url.openConnection();

     long size = con.getContentLength();

     length = size;

     return length;

   }

  }

4 向Web站点发送GET请求、POST请求,并从Web站点取得相应的示例

  public class TestGetPost

{

  public static String sendGet(String url,String param)

 {

   String result = "";

   BufferedReader in = null;

   try

   {

     String urlName = url + "?" +param;

    URL   realUrl = new URL(urlName);

    URLConnection conn = realUrl.openConnection();

    conn.setRequestProperty("accept","*/*");

    conn.setRequestProperty("connection","Keep-Alive");

    conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");

   conn.connect();

   Map<String, List<String>> map = conn.getHeaderFields();

   for(String key : map.keySet())

   {

      System.out.println(key+"--->"+map.get(key));

   }

   in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

   String line;

   while((line = in.readLine())!=null)

  {

    result +="\n"+line;

 }

   }

  catch(Exception e)

   {

     System.out.println("发送GET请求出现异常"+e);

     e.printStackTrace();

  }

  finally

  {

    try

    {

      if(in != null)

      {

       in.close();

     }

   }

   catch(IOException ex)

   {

     ex.printStackTrace();

   }

  }

return result;

 }

}

 

public static String sendPost(String url,String param)

 {

   PrintWriter out = null;

   BufferedReader in= null;

  String result = "";

  try

  {

    URL   realUrl = new URL(url);

   URLConnection conn = realUrl.openConnection();

   conn.setRequestProperty("accept","*/*");

   conn.setRequestProperty("connection","Keep-Alive");

   conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");

   conn.setDoOutput(true);

   conn.setDoInput(true);

   out = new PrintWriter(conn.getOutputStream());

   out.print(param);

   out.flush();

   in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

  String line;

  while((line = in.readLine()) != null)

  {  

    result + ="\n"+line;

 }

  }

catch(Exception e)

 {

   System.out.println("发送POST请求出现异常"+e);

   e.printStackTrace();

 }

finally

 {

  try

 {

   if(out != null)

  {

    out.close();

 }

 if(in !=null)

 {

  in.close();

}

 }

catch(IOException ex)

{

  ex.printStackTrace();

}

 }

return result;

}

public static void main(String args[])

{

   String s =TestGetPost.sendGet("http://localhost:8888/abc/login.jsp",null);

   System.out.println(s);

  String s1= TestGetPost.sendPost(http://localhost:8888/abc/a.jsp,"user=李刚&pass=abc");

 System.out.println(s1);

}

抱歉!评论已关闭.