android开发http请求POST&GET封装工具

本文介绍了一个简单的安卓网络请求封装方案,包括GET和POST请求的方法实现,并提供了请求成功和失败的回调接口。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近一直想着封装个网络请求框架,但是看到有很多博客有封装而且还不错,于是就想着封装一个安卓带的,以便自己以后使用.
一,请求成功和失败回调接口

public interface OnResponseListner {
    void onSucess(String response);
    void onError(String error);
}
二,post&get请求方法工具类
public class HttpUtlis {
    /**
     *get请求封装
     */
    public static void getRequest(String url, Map<String,String> params, String encode,OnResponseListner listner) {
        StringBuffer sb = new StringBuffer(url);
        sb.append("?");
        if (params!=null && !params.isEmpty()){
            for (Map.Entry<String,String> entry:params.entrySet()) {    //增强for遍历循环添加拼接请求内容
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            sb.deleteCharAt(sb.length()-1);
            if (listner!=null) {
                try {
                    URL path = new URL(sb.toString());
                    if (path!=null) {
                        HttpURLConnection con = (HttpURLConnection) path.openConnection();
                        con.setRequestMethod("GET");    //设置请求方式
                        con.setConnectTimeout(3000);    //链接超时3秒
                        con.setDoOutput(true);
                        con.setDoInput(true);
                        OutputStream os = con.getOutputStream();
                        os.write(sb.toString().getBytes(encode));
                        os.close();
                        if (con.getResponseCode() == 200) {    //应答码200表示请求成功
                            onSucessResopond(encode, listner, con);
                        }
                    }
                } catch (Exception error) {
                    error.printStackTrace();
                    onError(listner, error);
                }
            }
        }
    }

    /**
     * POST请求
     */
    public static void postRequest(String url,Map<String,String> params,String encode,OnResponseListner listner){
        StringBuffer sb = new StringBuffer();
        if (params!=null && !params.isEmpty()){
            for (Map.Entry<String,String> entry: params.entrySet()) {
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
                sb.deleteCharAt(sb.length()-1);
        }
        if (listner!=null) {
            try {
                URL path = new URL(url);
                if (path!=null){
                    HttpURLConnection con = (HttpURLConnection) path.openConnection();
                    con.setRequestMethod("POST");   //设置请求方法POST
                    con.setConnectTimeout(3000);
                    con.setDoOutput(true);
                    con.setDoInput(true);
                    byte[] bytes = sb.toString().getBytes();
                    OutputStream outputStream = con.getOutputStream();
                    outputStream.write(bytes);
                    outputStream.close();
                    if (con.getResponseCode()==200){
                        onSucessResopond(encode, listner,  con);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                onError(listner, e);
            }
        }
    }

    private static void onError(OnResponseListner listner,Exception onError) {
        listner.onError(onError.toString());
    }

    private static void onSucessResopond(String encode, OnResponseListner listner, HttpURLConnection con) throws IOException {
        InputStream inputStream = con.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//创建内存输出流
        int len = 0;
        byte[] bytes = new byte[1024];
        if (inputStream != null) {
            while ((len = inputStream.read(bytes)) != -1) {
                baos.write(bytes, 0, len);
            }
            String str = new String(baos.toByteArray(), encode);
            listner.onSucess(str);
        }
    }

}

三,activity中使用直接类名静态方法调用

   String url="";
    String encode="utf-8";
    public void GET(View view){
        Map<String,String> map=new HashMap<>();
        map.put("userName","");
        map.put("pwd","");
        HttpUtlis.getRequest(url, map,encode, new OnResponseListner() {
            @Override
            public void onSucess(String response) {

            }

            @Override
            public void onError(String error) {

            }
        });
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值