Android httpUrlConnection的基本使用

今天,简单讲讲Android HttpUrlConnection的使用。

 

我在项目里是使用OK HTTP的,但是最近发现使用OK HTTP好多不知道的问题,感觉自己对基本的网络请求不是很好的掌握,所以学习一下基本的网络请求类:HttpUrlConnection。

一,HttpURLconnection的介绍
在Android开发中网络请求是最常用的操作之一, Android SDK中对HTTP(超文本传输协议)也提供了很好的支持,这里包括两种接口: 
1、标准Java接口(java.NET) —-HttpURLConnection,可以实现简单的基于URL请求、响应功能; 
2、Apache接口(org.appache.http)—-HttpClient,使用起来更方面更强大。

但在android API23的SDK中Google将HttpClient移除了。Google建议使用httpURLconnection进行网络访问操作。

HttpURLconnection是基于http协议的,支持get,post,put,delete等各种请求方式,最常用的就是get和post,下面针对这两种请求方式进行讲解。
 

一.get请求

new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            String url = "https://www.baidu.com/";
            URL url = new URL(url);
            //得到connection对象。
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //设置请求方式
            connection.setRequestMethod("GET");
            //连接
            connection.connect();
            //得到响应码
            int responseCode = connection.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                //得到响应流
                InputStream inputStream = connection.getInputStream();
                //将响应流转换成字符串
                String result = is2String(inputStream);//将流转换为字符串。
                Log.d("kwwl","result============="+result);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}).start();
public String is2String(InputStream is){

                    //连接后,创建一个输入流来读取response
                    BufferedReader bufferedReader = new BufferedReader(new 
                     InputStreamReader(is,"utf-8"));
                    String line = "";
                    StringBuilder stringBuilder = new StringBuilder();
                    String response = "";
                    //每次读取一行,若非空则添加至 stringBuilder
                    while((line = bufferedReader.readLine()) != null){
                        stringBuilder.append(line);
                    }
                    //读取所有的数据后,赋值给 response
                    String response = stringBuilder.toString().trim();
return response 


}

get请求的使用方法如上。如果需要传递参数,则直接把参数拼接到url后面,其他完全相同,如下:

String url = "https://www.baidu.com/?userName=zhangsan&password=123456";

注意点: 
1,url与参数之间用?隔开。 
2,键值对中键与值用=连接。 
3,两个键值对之间用&连接

分析: 
1, 使用connection.setRequestMethod(“GET”);设置请求方式。 
2, 使用connection.connect();连接网络。请求行,请求头的设置必须放在网络连接前。 
3, connection.getInputStream()只是得到一个流对象,并不是数据,不过我们可以从流中读出数据,从流中读取数据的操作必须放在子线程。 
4, connection.getInputStream()得到一个流对象,从这个流对象中只能读取一次数据,第二次读取时将会得到空数据。
 

 

二.POST 请求

new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            URL url = new URL(getUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");//设置请求方式为POST
            connection.setDoOutput(true);//允许写出
            connection.setDoInput(true);//允许读入
            connection.setUseCaches(false);//不使用缓存
            connection.connect();//连接
            int responseCode = connection.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                InputStream inputStream = connection.getInputStream();
                String result = is2String(inputStream);//将流转换为字符串。
                Log.d("kwwl","result============="+result);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}).start();

注:post请求与get请求有很多相似,只是在连接之前多了一些设置,两者可以对比学习使用。

三。POST传递键值对

new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            URL url = new URL(getUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST"); 
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.connect();

            String body = "userName=zhangsan&password=123456";
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
            writer.write(body);
            writer.close();

            int responseCode = connection.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                InputStream inputStream = connection.getInputStream();
                String result = is2String(inputStream);//将流转换为字符串。
                Log.d("kwwl","result============="+result);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}).start();

分析: 
1,post方式传递参数的本质是:从连接中得到一个输出流,通过输出流把数据写到服务器。 
2,数据的拼接采用键值对格式,键与值之间用=连接。每个键值对之间用&连接。

 

参考文章:https://blog.csdn.net/fightingXia/article/details/71775516

 

在这里,和一些喷子说一下,我写这些博客只是为了记录自己的知识,没有从其他看的人那里得到什么好处。如果不喜欢,就不要看。不要留一些让我不舒服的评论。又没有人强迫你们来看我的博客。

 

Android httpUrlConnection的基本使用就讲完了。

 

就这么简单。

  • 12
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值