URL的介绍使用和URLConnection的使用

35 篇文章 0 订阅

URl访问网络资源与URLConnection网络请求提交

URL简介

URL就是一个网络资源定位器,通过URL我们可以找到具体的网络资源(包括Web页、文本文件、图形文件、声频片段等等)。

URL的基本表示格式是:protocol://hostname:/resourcename#anchor

    protocol: 使用的协议,它可以是httpftptelnet等。
    hostname:主机名 域名部分:指定域名服务器(DNS)能访问到的WWW服务的计算机。
    port: 端口号,是可选的,表示所连的端口号,如缺省,将连接到协议缺省的端口,例如:http协议的默认端口号为80
    resourcename: 资源名,是主机上能访问到的目录或文件。
    anchor :标记,也是可选的,它指定文件中的有特定标记的位置



URL类的方法

String getFile();获取url对应的资源名

String getHost();获取url对应的主机名

String getPath();获取URl的路径部分

int getPort();获取URl的端口号

String getProtocol();获取url的协议名

String getQuery();获取URl查询的字符部分

URlConnection openConnection();返回URlConnection对象,它表示到URL所应用的远程对象的连接,通过URLConnection可进行网络请求

InputStream openStream();打开URL连接,返回读取该资源的InpuStream字节输入流对象,可通过数据流读取数据,只能读取网络资源

 

获取字节输入流读取数据的实例:

布局文件

<?xmlversion="1.0"encoding="utf-8"?>

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical">

   

   <ImageView

        android:id="@+id/showurlImage"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:src="@drawable/abc_ab_share_pack_mtrl_alpha"/>

</LinearLayout>

 

Activity文件

 

public classGetURLImage extends Activity {

    ImageViewshowurlImage;

    private Bitmapbitmap;

    @Override

    protected void onCreate(BundlesavedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_geturlimage);

        showurlImage=(ImageView)findViewById(R.id.showurlImage);

        showImage();

    }

   

    public void showImage(){

        new Thread(new Runnable() {

           

            @Override

            public void run() {

                try {

                    InputStreamis=null;

                    URLurl=newURL("http://h.hiphotos.baidu.com/image/pic/item/dc54564e9258d109a4d1165ad558ccbf6c814d23.jpg");

                    is=url.openStream();

                    bitmap=BitmapFactory.decodeStream(is);

                    handler.sendEmptyMessage(1000);

                    is=url.openStream();

                    Filefile=Environment.getExternalStorageDirectory();

                    FilefileImage=newFile(file,"image.jpg");

                    FileOutputStreamoput=newFileOutputStream(fileImage);//输出流输出到fileImage

                    byte[] b=newbyte[1024];

//                  inthasread=0;

is.read(b);//将输入流中的数据读取并存入字节数组中,返回值是读取的byte数,若返回-1则是无数据可读了

                    while((is.read(b))>0){

                        oput.write(b);

                    }

                    is.close();

                    oput.close();

                   

                }catch(Exception e) {

                    e.printStackTrace();

                }      

            }

        }).start();

    }

    private Handlerhandler=newHandler(){

        public voidhandleMessage(android.os.Message msg) {

            if(msg.what==1000&&bitmap!=null){

                showurlImage.setImageBitmap(bitmap);

            }

        };

    };

}

使用URLConnection进行网络请求

URlConnection的使用步骤

(1)  通过URL对象的openConnection()拿到URLConnection对象

(2)  设置表URlCopnnection的参数和普通请求属性

(3)  设置请求方式:若是get请求,则使用connect()方法建立和远程资源的连接即可;若是POST请求,则需要通过getOutputStream()获取URlConnection的输出流,将参数通过输出流传递。

(4)  远程资源变为可用,程序可以访问远程资源的头字段,或通过getInputStream()获取输入流,从而获取了远程资源。

 

在建立和远程资源的实际连接之前,程序可以通过如下方法来设置请求头字段:

setAllowUserInteraction:设置该URLConnection的allowUserInteraction请求头字段的值。

setDoInput:设置该URLConnection的doInput请求头字段的值。

setDoOutput:设置该URLConnection的doOutput请求头字段的值。

setIfModifiedSince:设置该URLConnection的ifModifiedSince请求头字段的值。

setUseCaches:设置该URLConnection的useCaches请求头字段的值。

除此之外,还可以使用如下方法来设置、或增加通用头字段:

setRequestProperty(String key,String value):设置该URLConnection的key请求头字段的值为value。如下代码所示:

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

addRequestProperty(String key,String value):为该URLConnection的key请求头字段的增加value值,该方法并不会覆盖原请求头字段的值,而是将新值追加到原请求头字段中。

当远程资源可用之后,程序可以使用以下方法用于访问头字段和内容:

Object getContent():获取该URLConnection的内容。

String getHeaderField(String name):获取指定响应头字段的值。

getInputStream():返回该URLConnection对应的输入流,用于获取URLConnection响应的内容。

getOutputStream():返回该URLConnection对应的输出流,用于向URLConnection发送请求参数。

注意:如果既要使用输入流读取URLConnection响应的内容,也要使用输出流发送请求参数,一定要先使用输出流,再使用输入流。

getHeaderField方法用于根据响应头字段来返回对应的值。而某些头字段由于经常需要访问,所以Java提供了以下方法来访问特定响应头字段的值:

getContentEncoding:获取content-encoding响应头字段的值。

getContentLength:获取content-length响应头字段的值。

getContentType:获取content-type响应头字段的值。

getDate():获取date响应头字段的值。

getExpiration():获取expires响应头字段的值。

getLastModified():获取last-modified响应头字段的值。

 

实例

布局文件:

<?xmlversion="1.0"encoding="utf-8"?>

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical">

   <ScrollView

        android:layout_width="match_parent"

        android:layout_height="match_parent">

        <LinearLayout

             android:layout_width="match_parent"

            android:layout_height="match_parent"

            android:orientation="vertical">

            <LinearLayout

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:orientation="horizontal">

                <TextView

                    android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:text="直接get请求结果:"

                />

                <TextView

                    android:id="@+id/jsonGetRequesgt"

                    android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                />

            </LinearLayout>

            <LinearLayout

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:orientation="horizontal">

                <TextView

                    android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:text="get请求结果:"

                />

                <TextView

                    android:id="@+id/showGetRequesgt"

                    android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                />

            </LinearLayout>

            <LinearLayout

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:orientation="horizontal">

                <TextView

                    android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:text="post请求结果:"

                />

                <TextView

                    android:id="@+id/showPostRequesgt"

                    android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                />

            </LinearLayout>

        </LinearLayout>

</ScrollView>

</LinearLayout>

 

Activity类:

public class MyUrlConnection extends Activity{

    TextViewshowGetRequesgt,showPostRequesgt,jsonGetRequesgt;

    @Override

    protectedvoid onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

          setContentView(R.layout.activity_myurlconnection);

          showGetRequesgt=(TextView)findViewById(R.id.showGetRequesgt);

          showPostRequesgt=(TextView)findViewById(R.id.showPostRequesgt);

          jsonGetRequesgt=(TextView)findViewById(R.id.jsonGetRequesgt);

          new Thread(new Runnable() {

           

            @Override

            publicvoid run() {

                Stringurl ="http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo";

                String json =URLConnectionUtil.loadJSON(url);

                Message msgg=new Message();

                msgg.what=99;

                msgg.obj=json;

                handler.sendMessage(msgg);

               

                StringgetResutl=URLConnectionUtil.GET(

                        "http://api.geonames.org/citiesJSON","north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo");

                Messagemsg=new Message();

                msg.what=100;

                msg.obj=getResutl;

                handler.sendMessage(msg);

               

                StringpostResutl=URLConnectionUtil.post("http://api.geonames.org/citiesJSON","north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo");

                Messagemsgs=new Message();

                msgs.what=101;

                msgs.obj=postResutl;

                handler.sendMessage(msgs);

            }

        }).start();

    }

   

    privateHandler handler=new Handler(){

        publicvoid handleMessage(android.os.Message msg) {

            if(msg.what==99){

                jsonGetRequesgt.setText((msg.obj).toString());

            }elseif(msg.what==100){

                showGetRequesgt.setText((msg.obj).toString());

            }else{

                showPostRequesgt.setText((msg.obj).toString());

            }

        };

    };

}

工具类:

public class URLConnectionUtil {

    //get请求实现

    publicstatic String loadJSON (String url) {

       StringBuilder json = new StringBuilder();

       try {

           URL oracle = new URL(url);

           URLConnection yc = oracle.openConnection();

           BufferedReader in = new BufferedReader(new InputStreamReader(

                                       yc.getInputStream()));

           //注意下面这种输入流的读取形式,

           String inputLine = null;

           while ( (inputLine = in.readLine()) != null) {

               json.append(inputLine);

           }

           in.close();

        }catch (MalformedURLException e) {

        }catch (IOException e) {

        }

       return json.toString();

    }

   

    //URLConnection的get请求

    publicstatic String GET(String URl,String params){

        Stringresult=null;

        BufferedReaderreader=null;

        try{

            Stringurls=URl+"?"+params;

            URLurl=new URL(urls);//是拼接参数后的url

            URLConnectionconnect=url.openConnection();//获取了URLConnection对象了,还没有建立连接

            connect.setRequestProperty("accept","*/*");//设置请求的头字段的值

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

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

            connect.connect();//建立连接,之后就可以通过数据流获取返回的响应结果了

            reader=newBufferedReader(new InputStreamReader(connect.getInputStream()));//获取URLConnection的输入流

            StringBuilderbuilder=new StringBuilder();

            Stringline;

            while((line=reader.readLine())!=null){

                builder.append("\n"+line);

            }

            result=builder.toString();

        }catch(Exceptione){

            e.printStackTrace();

        }finally{

                try{

                    if(reader!=null){

                        reader.close();

                    }

                }catch (IOException e) {

                    e.printStackTrace();

                }

        }

        returnresult;

    }

    //URLConnection的Post请求

    publicstatic String post(String url,String params){

        Stringresult=null;

        BufferedWriterwriter=null;

        BufferedReaderreader=null;

        try{

            URLurll=new URL(url);

            URLConnectionconnection=urll.openConnection();//获取URLConnection对象

            connection.setRequestProperty("accept","*/*");//设置请求的头字段的值

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

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

            connection.setDoInput(true);//URlConnection网络请求时必须设置的,设置可以读写

            connection.setDoOutput(true);//URlConnection网络请求时必须设置的,设置可以读写

            writer=newBufferedWriter(new OutputStreamWriter(connection.getOutputStream()));//获取输出流对象,用于输出参数,即传递参数

            writer.write(params);

            writer.flush();//将缓冲区中的数据强制写入输出流

            reader=newBufferedReader(new InputStreamReader(connection.getInputStream()));//获取URLConnection的输入流

//          reader.readLine()//读取一行数据,当没有数据可读是返回null;

            StringBuilderbuilder=new StringBuilder();

            Stringline;

            while((line=reader.readLine())!=null){

                builder.append("\n"+line);

            }

            result=builder.toString();

        }catch(Exceptione){

            e.printStackTrace();

        }finally{

            try{

                if(writer!=null){

                    writer.close();

                }

                if(reader!=null){

                    reader.close();

                }

            }catch(Exceptione){

                e.printStackTrace();

            }

        }

        returnresult;

    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值