码迷,mamicode.com
首页 > 编程语言 > 详细

Java Socket应用(三)——java中URL的应用

时间:2015-06-27 09:58:03      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:java   socket   url   应用   

转载请注明http://blog.csdn.net/uniquewonderq

技术分享

如何使用呢?

package com.test;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

public class test{
    public static void main(String[] args) {
        try {
            //创建一个URL实例
            URL baidu=new URL("http://www.baidu.com");
            URL url=new URL(baidu, "/index.html?username=wonderq#test");
            System.out.println("协议:"+url.getProtocol());
            System.out.println("主机:"+url.getHost());
            //如果未指定端口号,则使用默认端口号,此时getport返回值为-1
            System.out.println("端口号:"+url.getPort());
            System.out.println("文件路径:"+url.getPath());
            System.out.println("文件名称;"+url.getFile());
            System.out.println("相对路径:"+url.getRef());
            System.out.println("查询字符串:"+url.getQuery());
        } catch (MalformedURLException ex) {
            Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
        }
     }
}

输出结果:


run:
协议:http
主机:www.baidu.com
端口号:-1
文件路径:/index.html
文件名称;/index.html?username=wonderq
相对路径:test
查询字符串:username=wonderq

技术分享


测试程序:

package com.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

public class test{
    public static void main(String[] args) {
        try {
            //创建URL实例
            URL url=new URL("http://www.baidu.com");
            //通过URL的openStream()方法获取对象所表示的资源的字节输入流
            InputStream is=url.openStream();
            //将字节输入流转化为字符输入流
            InputStreamReader isr=new InputStreamReader(is,"utf-8");
            //为字符输入流添加缓冲
            BufferedReader br=new BufferedReader(isr);
            //定义字符串保存读取的数据
            String data= br.readLine();
            while(data!=null){
                System.out.println(data);
                data=br.readLine();
            }
            br.close();
            isr.close();
            is.close();
        } catch (MalformedURLException ex) {
            Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
        }
     }
}

输出结果:

技术分享



将上述结果保存到一个文本中,更改后缀名为.html。然后双击该文本。

如:技术分享

运行测试结果:

技术分享

















版权声明:本文为博主原创文章,未经博主允许不得转载。

Java Socket应用(三)——java中URL的应用

标签:java   socket   url   应用   

原文地址:http://blog.csdn.net/uniquewonderq/article/details/46653623

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!