android 原生AsyncTask异步任务封装网络请求

前言:

最近在做安卓新项目 但是要用到老技术 有点尴尬哈 因为之前手写的网络框架都是开一个线程然后用handler来实现线程之前的通信 现在我改了用 AsyncTask 来实现:做个笔记 因为是很老的技术 我就不当时博客了

效果图

具体实现:

网络连接

ini 复制代码
package com.example.myapplication.http;
import android.text.TextUtils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
/**
 * Created by xuqing on Date: 2022/11/2
 */
public class NetWorkRequest {
    private int dkpdpConnectTime =10000;
    private int dkpdpReadTime =10000;

    /**
     * ch
     * @param requestUrl
     * @param requestMethod
     */
    public NetResponse qecrnNetWordRequst(String requestUrl, String requestMethod, String contextType, String body, Map<String, String> headerMap){
        HttpURLConnection connection = null;
        try {
            URL url = new URL(requestUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(dkpdpConnectTime);
            connection.setReadTimeout(dkpdpReadTime);
            connection.setRequestMethod(requestMethod);
            connection.setDoInput(true);//可读入
            connection.setDoOutput(true);//可写出
            connection.setUseCaches(false);//不缓存
            if(!TextUtils.isEmpty(contextType)){
                connection.setRequestProperty("Content-Type", contextType);
            }
            if(headerMap!=null && headerMap.size()>0){
                for (String key:headerMap.keySet()){
                    connection.setRequestProperty(key,headerMap.get(key));
                }
            }
            connection.connect();//建立连接
            if(!TextUtils.isEmpty(body)){
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(),"UTF-8"));
                if(writer!=null){
                    writer.write(body);
                    writer.close();
                }
            }
            return qecrnGetNetResponse(connection);
        } catch (Throwable e) {
            e.printStackTrace();
            return qecrnExceptionResponse(connection,e);
        }

    }

    /**
     * 正常返回,获取response 对象
     * @param conn
     * @return
     */
    private NetResponse qecrnGetNetResponse(HttpURLConnection conn){
        NetResponse response = new NetResponse();
        try {
            if(conn == null){
                return null;
            }
            response.dkpdpResponseCode = conn.getResponseCode();

            if(response.dkpdpResponseCode == HttpURLConnection.HTTP_OK){
                response.dkpdpResponseContent = qecrnGetResponeString(conn.getInputStream());
                response.dkpdpResponseCode = 200;//强制修改为200,判断200为成功接收就好了。
            }else{
                response.dkpdpResponseContent = qecrnGetResponeString(conn.getErrorStream());
            }
        } catch (Throwable e) {
            response.dkpdpResponseCode = -1;
            response.dkpdpResponseContent = e.getMessage();
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 异常返回,获取response 对象
     * @param conn
     * @param e
     * @return
     */
    private NetResponse qecrnExceptionResponse(HttpURLConnection conn, Throwable e){
        if(conn != null){
            conn.disconnect();
        }
        if(e == null){
            return null;
        }
        e.printStackTrace();
        NetResponse response = new NetResponse();
        response.dkpdpResponseCode = -2;
        response.dkpdpResponseContent = e.getMessage();
        return response;
    }

    private String qecrnGetResponeString(InputStream is){
        String buf;
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
            StringBuilder sb = new StringBuilder();
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            buf = sb.toString();
            return buf;

        } catch (Throwable e) {
            return "";
        }

    }
}

异步任务 GET

typescript 复制代码
package com.example.myapplication.http;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;




/**
 * Created by kunge hu on 2016/11/1.
 */
public class GetTask extends AsyncTask<Void, Void, String> {
    private static final String TAG = "GetTask";
    private HttpRequestCallBack listener;
    private String url;
    private Map<String, String> getmapparams;
    private String type;


    /**
     *
     * @param url
     * @param listener
     */
    public GetTask( String url,HttpRequestCallBack listener) {
        this.listener = listener;
        this.url = url;
    }
    /***
     *
     * @param url
     * @param type
     * @param getmapparams
     * @param listener
     */
    public GetTask(final String url, final String type, final Map<String, String> getmapparams, HttpRequestCallBack listener) {
        this.url = url;
        this.listener = listener;
        this.getmapparams=getmapparams;
        this.type=type;
    }

    @SuppressLint("NewApi")
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected String doInBackground(Void... params) {
        try {
            String geturl="";
            if(getmapparams!=null){
                geturl= RequestUtil.clwuyGetUrl(url,getmapparams);
            }else{
                geturl=url;
            }
            NetWorkRequest request = new NetWorkRequest();
            Map<String, String> headerMap=new HashMap<>();
            headerMap.put("x-method","get");
            headerMap.put("x-request",type);
            String contextType="application/json;charset=utf-8";
            NetResponse response =request.qecrnNetWordRequst(geturl,"GET",contextType,"",headerMap);
            Log.e(TAG, "doInBackground:response "+response.dkpdpResponseContent );

            if(response.dkpdpResponseCode==200){
                return  response.dkpdpResponseContent;
            }else{
                return null;
            }

        } catch (Exception e) {
            Log.e("kunge.hu", "GetTask Exception:" + e.toString());
        }
        return null;
    }
    @SuppressLint("NewApi")
    @Override
    protected void onPostExecute(String t) {

        try {
            if(!TextUtils.isEmpty(t)){
                JSONObject jsonObject=new JSONObject(t);
                listener.clwuyHttpCallBackListener(t);
              }else{
                Log.e(TAG, "onPostExecute: "+"网络服务器失败" );
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

异步任务post

typescript 复制代码
package com.example.myapplication.http;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;

/**
 * 作者:xuqing
 * 时间:
 * 邮箱:1693891473@qq.com
 * 说明:post请求异步任务
 */
public class PostTask extends AsyncTask<Void, Void, String> {
    private static final String TAG = "GetTask";
    private HttpRequestCallBack listener;
    private String url;
    private Map<String, String> getmapparams;
    private String type;


    public PostTask(final String url,   HttpRequestCallBack listener) {
        this.url = url;
        this.listener = listener;
    }

    public PostTask(final String url, final String type, final Map<String, String> getmapparams, HttpRequestCallBack listener) {
        this.url = url;
        this.listener = listener;
        this.getmapparams=getmapparams;
        this.type=type;
    }

    @SuppressLint("NewApi")
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected String doInBackground(Void... params) {
        try {
            String body="";
            if(getmapparams!=null){
                body= RequestUtil.clwuyGetPostBodyFormParameMap(getmapparams);
            }

            NetWorkRequest request = new NetWorkRequest();
            Map<String, String> headerMap=new HashMap<>();
            headerMap.put("x-method","post");
            headerMap.put("x-request",type);
            String contextType="application/json;charset=utf-8";
            NetResponse response =request.qecrnNetWordRequst(url,"POST",contextType,body,headerMap);
            Log.e(TAG, "doInBackground:response "+response.dkpdpResponseContent );
            if(response.dkpdpResponseCode==200){
                return  response.dkpdpResponseContent;
            }else{
                return null;
            }

        } catch (Exception e) {
            Log.e("kunge.hu", "GetTask Exception:" + e.toString());
        }
        return null;
    }
    @SuppressLint("NewApi")
    @Override
    protected void onPostExecute(String t) {

        try {
            if(!TextUtils.isEmpty(t)){
                JSONObject jsonObject=new JSONObject(t);
                listener.clwuyHttpCallBackListener(t);
            }else{
                Log.e(TAG, "onPostExecute: "+"网络服务器失败" );
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

对外层调用方法

typescript 复制代码
package com.example.myapplication.http;
import java.util.Map;


/**
 * 作者:xuqing
 * 时间:2023年11月28日10:17:12
 * 邮箱:1693891473@qq.com
 * 说明:对外层调用的方法
 */
public class NetCtrl {
    public static void get(final String url,  HttpRequestCallBack listener) {
        new GetTask(url, listener).execute();
    }
    public static void get(final String url, final String type, final Map<String, String> params, HttpRequestCallBack listener) {
        new GetTask( url,type, params, listener).execute();
    }
    public static  void post(final String url, HttpRequestCallBack listener){
        new PostTask( url, listener).execute();
    }
    public static  void post(final String url, final String type,
                             final Map<String, String> params, HttpRequestCallBack listener){
        new PostTask( url,type, params, listener).execute();
    }
}

在MainActivity测试请求

get

typescript 复制代码
        //带请求参数
        NetCtrl.get(url, "", null, new HttpRequestCallBack() {
            @Override
            public void clwuyHttpCallBackListener(String result) {
                Log.e(TAG, "clwuyHttpCallBackListener: result-- >"+result );

            }
            @Override
            public void clwuyHttpRequestFail(String errorString, int code) {
            }
        });


        //不带请求参数
        NetCtrl.get(url, new HttpRequestCallBack() {
            @Override
            public void clwuyHttpCallBackListener(String result) {
                Log.e(TAG, "clwuyHttpCallBackListener: result-- >"+result );

            }
            @Override
            public void clwuyHttpRequestFail(String errorString, int code) {
            }
        });

post

typescript 复制代码
  NetCtrl.post(url, "", null, new HttpRequestCallBack() {
            @Override
            public void clwuyHttpCallBackListener(String result) {
                Log.e(TAG, "post clwuyHttpCallBackListener: result-- >"+result );

            }
            @Override
            public void clwuyHttpRequestFail(String errorString, int code) {
            }
        });
        NetCtrl.post(url, new HttpRequestCallBack() {
            @Override
            public void clwuyHttpCallBackListener(String result) {
                Log.e(TAG, "clwuyHttpCallBackListener: "+"result  -- >  " +result );


            }

            @Override
            public void clwuyHttpRequestFail(String errorString, int code) {

            }
        });
        
        

项目地址:

码云 :gitee.com/qiuyu123/as...

相关推荐
大白要努力!几秒前
Android opencv使用Core.hconcat 进行图像拼接
android·opencv
天空中的野鸟1 小时前
Android音频采集
android·音视频
小白也想学C2 小时前
Android 功耗分析(底层篇)
android·功耗
曙曙学编程2 小时前
初级数据结构——树
android·java·数据结构
闲暇部落4 小时前
‌Kotlin中的?.和!!主要区别
android·开发语言·kotlin
诸神黄昏EX6 小时前
Android 分区相关介绍
android
大白要努力!7 小时前
android 使用SQLiteOpenHelper 如何优化数据库的性能
android·数据库·oracle
Estar.Lee7 小时前
时间操作[取当前北京时间]免费API接口教程
android·网络·后端·网络协议·tcp/ip
Winston Wood8 小时前
Perfetto学习大全
android·性能优化·perfetto
Dnelic-11 小时前
【单元测试】【Android】JUnit 4 和 JUnit 5 的差异记录
android·junit·单元测试·android studio·自学笔记