URLConnection 和 HttpURLConnection

      URLConnection 和 HttpURLConnection 是最基础的网络编程接口。

       URLConnection  是HttpURLConnection  的基类, 首先介绍一下URLConnection  是HttpURLConnection  的重要字段。

一   URLConnection 和 HttpURLConnection 的重要字段

        1. 连接参数

     protected boolean doInput   是否允许输入

         protected boolean doOutput  是否允许输出

     protected boolean connected   此连接对象是否已经和服务端连接成功

     protected boolean useCaches   是否允许缓存
          

其他还有关于连接超时, 读取超时等字段

       2. 连接请求的方法

           GET: 请求URL资源   

           POST:  在URL标识资源后添加资源

           HEAD:请求URL 标识资源的响应消息报头

           PUT:  请求服务器保存资源, 以URL 为标识

           DELETE: 删除URL标识的资源

          TRACE: 请求服务器回送收到的请求信息, 主要用于测试

          CONNECT :未使用

          OPTION: 请求查询服务器性能。


二   HTTPURLconnection的处理流程

       1.  从URL 对象的openConnection 方法返回连接对象

       2.  设置参数和一般的请求属性

            一定要用HttpURLConnection的对象的setRequestMethod方法设置连接方式

    如:urlConnection.setRequestMethod("GET");//必须大写

    设置一般属性的方法 setRequestProperty 在URLConnection 中定义。

          1)  public voidsetRequestProperty(String key, String value)

               如果有旧值,更新为新值。

         2) public voidaddRequestProperty(String key,  String value)

         增加新值,不会更新旧值。

       3.   使用connect() 方法 建立实际连接

             这时就和远程服务器连接上了。

       4.  从连接中获得输入,输出流。

           如: 

       InputStream inputStream=urlConnection.getInputStream();

           或者:

           OutputStream outputStream=urlConnection.getOutputStream();

       5. 处理输入输出

       6. 关闭输入输出流,关闭连接


三  实例程序

      此实例程序用HTTP 协议从网络下载一个图片并显示。

public class MainActivity extends AppCompatActivity {
    private ImageView view;
    private Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        view=(ImageView)findViewById(R.id.view);
        btn=(Button)findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String imgUrl = "http://p1.meituan.net/deal/a5c0180d48419fe09f8edb0f267a7e7767069.jpg";
                new asyn().execute(imgUrl);
            }
        });
    }
     public void onResume(){
         super.onResume();
    }
    private Bitmap getImageBitMap(String url){
        URL imgurl = null;
        Bitmap bitmap = null;

        HttpURLConnection urlConnection;
        try {
            imgurl=new URL(url);
            urlConnection=(HttpURLConnection)imgurl.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();
            InputStream inputStream=urlConnection.getInputStream();
            OutputStream outputStream=urlConnection.getOutputStream();
            bitmap = BitmapFactory.decodeStream(inputStream);
            inputStream.close();
            urlConnection.disconnect();
        } catch( IOException e){
             e.printStackTrace();
        }
        return bitmap;
    }


    class asyn extends AsyncTask<String, Void, Bitmap>{
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            view.setImageBitmap(null);
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            if (result != null) {
                view.setImageBitmap(result);
            }
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap b = getImageBitMap(params[0]);
            return b;
        }
    }
}




不要忘了在AndroidManifest.xml 中设置网络权限。


 <uses-permission android:name ="android.permission.INTERNET"/>



四 UML 及其说明

getContentLength()返回 content-length 头字段的值
getContentType() 返回 content-type 头字段的值
getContentEncoding() 返回content-Encoding 头字段的值
getExpiration() 返回expires 头字段的值, 表示该URL 引用资源的有效期限
getDate() 返回date 头字段的值, 表示该 URL 引用的资源的发送日期
getLastModified() 返回 last-modified 头字段的值, 资源最后修改的时间


以下几个方法去获得不同格式的某个 头键的值: getHeaderField,getHeaderFieldInt(String name, int Default)
getHeaderFieldLong(String name, long Default),getHeaderFieldDate(String name, long Default)


以下两个方法可以遍历头字段:
getHeaderFieldKey(int n) 获得第n个头字段的键
getHeaderField(int n) 获得第n个头字段的值


getContent(): Object  得到URL 连接的内容。 object 类型与content_type 决定


getPermission():Permission 代表建立此 URLConnection 表示的连接所需的权限的权限对象.


toString(): 返回此连接的String 格式


setDefaultAllowUserInteraction(boolean defaultallowuserinteraction)
将未来的所有 URLConnection 对象的 allowUserInteraction 字段的默认值设置为指定的值


setRequestProperty(String key, String value) 设置连接的一般属性, 会更新已存在的键
addRequestProperty(String key, String value) 设置连接的一般属性, 保留已存在的键


ContentHandlerFactory:此接口定义内容处理程序的工厂。此接口的实现应该将 MIME 类型映射到 ContentHandler 的实例中





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值