Android URLConnection发送Get请求 HttpGet封装

一.使用URLConnection发送Get请求

1.与服务器建立连接:

URLConnection connection=new URL(“https://www.baidu.com/”).openConnection();

2.设置请求头(Cookie亦可通过请求头设置):

connection.setRequestProperty(“Referer”,“https://www.baidu.com/”);
connection.setRequestProperty(“Cookie”,“BIDUPSID=844B9321236FFD30C304AE4CCEE0602A;BD_UPN=12314753”);

3.获取响应信息:

(1):建议使用StringBuilder拼接字符串;

(2):如果new了流对象不要忘记close。

StringBuilder response=new StringBuilder();
	
            InputStream is=connection.getInputStream();
            BufferedReader br=new BufferedReader(new InputStreamReader(is));
            String str;
            while ((str=br.readLine())!=null){
                response.append(str);
            }
            br.close();
            is.close();

return response.toString();

 

二.HttpGet封装

源码:

    static public String  HttpGet(String url,Map headers){

        try {
            //打开连接
            URLConnection connection=new URL(url).openConnection();

            //设置请求头
            if(headers!=null){
                Set<Map.Entry> set=headers.entrySet();
                for (Map.Entry entry:set) {
                    connection.setRequestProperty(entry.getKey().toString,entry.getValue().toString);
                }
            }
            //获取响应信息
            StringBuilder response=new StringBuilder();

            BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String str;
            while ((str=br.readLine())!=null){
                response.append(str);
            }
            br.close();

            //返回结果
            return response.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;

    }

调用:

Map headers=new HashMap();
headers.put("Referer","https://www.baidu.com/");
headers.put("Cookie","BIDUPSID=844B9321236FFD30C304AE4CCEE0602A;BD_UPN=12314753")
HttpGet("https://www.baidu.com/",headers);

 

三.android网络请求两大要素

1.申请网络权限:<uses-permission android:name="android.permission.INTERNET"></uses-permission>;

2.在子线程中访问网络。

转载于:https://www.cnblogs.com/cx98/p/7816358.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值