Android基于HttpURLConnection网络请求

HttpUrlConnection是继承UrlConnection的抽象类,是Android网络请求的标准类,下面分别介绍如何利用HttpUrlConnetion进项get和post请求:


1.get请求

private void getDataFromNetGet(final String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection=null;
                DataInputStream dis=null;
                try {
                    URL temUrl=new URL(url) ;
                    connection= (HttpURLConnection) temUrl.openConnection();
                    connection.setConnectTimeout(5000);//设置请求超时时间
                    connection.setRequestMethod("GET");//设置请求方式
                    connection.connect();//建立Http连接
                    if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
                        //获取响应流
                        dis=new DataInputStream(connection.getInputStream());
                        String result = dis.readUTF();
                        String resultUnicode=decodeUnicode(result);
                        //Handle通知UI线程更新界面
                        Message message = Message.obtain();
                        message.obj=resultUnicode;
                        message.what=GET_RESPONSE_SUCCESS;
                        mHandler.sendMessage(message);
                    }else{
                        Log.e("yufs","网络请求失败:"+connection.getResponseCode());
                    }
                } catch (MalformedURLException  e) {
                    e.printStackTrace();
                } catch(IOException e){
                    e.printStackTrace();
                }finally {
                    if(dis!=null){
                        try {
                            dis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if(connection!=null){
                        connection.disconnect();
                    }
                }
            }
        }).start();
}

HttpUrlConnection获取是通过URL对象调用系统封装好的openConnection()方法,返回一个UrlConnection(HttpUrlConnection的父类)对象,设置常规的参数,超时,请求方式为get,通过get的请求方式如果需要传递参数,只需要在请求地址后面以key=value的形式拼接参数,多个参数用&隔开。调用HttpUrlConnection的connect()打开连接,获取响应,更新UI,需要注意的是网络请求必须放在分线程中进行,最后通过Handler通知主线程更新数据


2.post请求,一般为提交表单,将请求参数封装在请求体,请求安全性相对可靠

private void getDataFromNetPost(final String url,Map<String,String> params){
        final byte[] data=getRequestData(params,"UTF-8").toString().getBytes();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DataInputStream dis=null;
                try {
                    URL temUrl=new URL(url);
                    HttpURLConnection connection= (HttpURLConnection) temUrl.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setConnectTimeout(5000);
                    connection.setDoOutput(true);//设置输出流,允许提交数据
                    connection.setDoInput(true);//设置输入流,允许读取响应
                    connection.setUseCaches(false);//post方式请求不允许缓存
                    //设置请求体的类型是文本类型
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    //向服务器提交请求体,此处实际打开连接了
                    OutputStream outputStream = connection.getOutputStream();
                    outputStream.write(data);
                    if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
                        dis=new DataInputStream(connection.getInputStream());
                        String result = dealResponseResult(dis);
//                        String resultUnicode=decodeUnicode(result);
                        //Handle通知UI线程更新界面
                        Message message = Message.obtain();
                        message.obj=result;
                        message.what=POST_RESPONSE_SUCCESS;
                        mHandler.sendMessage(message);
                    }else{
                        Log.e("yufs","网络请求失败:"+connection.getResponseCode());
                    }

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


需要注意的是在设置请求时,setDoOutput、setDoInput必须设置,post的请求参数最终是通过写入HttpURLConnecting中的getOutputStream()得到的输出流中的,传递参数的时候我们只需要得到一个Map对象就可以了,可能很奇怪为什么没有调用connect()方法,其实getOutputStream()调用的时候默认已经连接了,下面是参数的封装:

/**
 * 将参数封装为键值对
 * @param params
 * @param encode
 * @return
 */
public static StringBuffer getRequestData(Map<String, String> params, String encode) {
    StringBuffer stringBuffer = new StringBuffer();        //存储封装好的请求体信息
    try {
        for(Map.Entry<String, String> entry : params.entrySet()) {
            stringBuffer.append(entry.getKey())
                    .append("=")
                    .append(URLEncoder.encode(entry.getValue(), encode))
                    .append("&");
        }
        stringBuffer.deleteCharAt(stringBuffer.length() - 1);    //删除最后的一个"&"
    } catch (Exception e) {
        e.printStackTrace();
    }
    return stringBuffer;
}


其实看方法中封装的更get请求参数拼接基本一样,只不过请求参数放的位置不同罢了

源码提取:https://pan.baidu.com/s/1qXH2RyW    密码35xn

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值