动脑学院-网络请求框架

Posted 天耀106

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了动脑学院-网络请求框架相关的知识,希望对你有一定的参考价值。

1、网络抽象层接口
package lwl.tianyao.httpproject;

import java.util.Map;

/**
 * 网络抽象层接口
 */

public interface IHttpProcessor 

    void post(String url,Map<String,Object> params,final HttpCallback callback);

    void get(String url,Map<String,Object> params,final HttpCallback callback);

2、回调接口

package lwl.tianyao.httpproject;

/**
 * 回调接口
 */
public interface ICallback 

    void onSuccess(String result);

    void onFailure(String e);

3、HttpHelper

package lwl.tianyao.httpproject;

import java.net.URLEncoder;
import java.util.Map;

public class HttpHelper implements IHttpProcessor 

    private static HttpHelper instance;

    private HttpHelper()

    

    public static HttpHelper obtain()
        synchronized (HttpHelper.class)
            if(instance==null)
                instance=new HttpHelper();
            
        
        return instance;
    


    private static IHttpProcessor mHttpProcessor = null;

    public static void init(IHttpProcessor httpProcessor)
        mHttpProcessor = httpProcessor;
    


    @Override
    public void post(String url, Map<String, Object> params, HttpCallback callback) 
        final String finalUrl = appendParams(url,params);
        mHttpProcessor.post(finalUrl,params,callback);
    

    @Override
    public void get(String url, Map<String, Object> params, HttpCallback callback) 
        mHttpProcessor.post(url,params,callback);
    

    public static String appendParams(String url,Map<String,Object> params)
        if(params ==null || params.isEmpty())
            return url;
        

        StringBuilder urlBuilder = new StringBuilder(url);
        if(urlBuilder.indexOf("?")<=0)
            urlBuilder.append("?");
        else 
            if(!urlBuilder.toString().endsWith("?"))
                urlBuilder.append("&");
            
        

        for(Map.Entry<String,Object> entry:params.entrySet())
            urlBuilder.append("&"+entry.getKey()).append("=").append(encode(entry.getValue().toString()));

        
        return urlBuilder.toString();
    
    private static String encode(String str)
        try 
            return URLEncoder.encode(str,"utf-8");
        catch (Exception e)
            e.printStackTrace();
            throw new RuntimeException();
        
    


4、回调接口的实现

package lwl.tianyao.httpproject;

import com.google.gson.Gson;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 *  回调接口的实现
 *  1.必须想办法得到Result
 *  2.用户把返回string转换成调用层传入的参数化类型 Result
 */
public abstract class HttpCallback<Result> implements ICallback

    @Override
    public void onSuccess(String result) 
        Gson gson = new Gson();
        Class<?> clz =analysisClassInfo(this);
        Result objResult= (Result) gson.fromJson(result,clz);
        //objResult传回调用者
        onSuccess(objResult);

    

    public abstract void onSuccess(Result result);


    private static Class<?> analysisClassInfo(Object object)
        //getGenericSuperclass可以得到包含原始类型,参数化类型,数据类型,类型变量。
        Type genType = object.getClass().getGenericSuperclass();
        //获取参数化类型(<Result>)
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        return (Class<?>) params[0];

    

    @Override
    public void onFailure(String e) 

    

5、volley框架VolleyProcessor

package lwl.tianyao.httpproject;

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.Map;

public class VolleyProcessor implements IHttpProcessor 

    private static RequestQueue mQueue = null;

    public VolleyProcessor(Context context)
        mQueue = Volley.newRequestQueue(context);
    

    @Override
    public void post(String url, Map<String, Object> params, final HttpCallback callback) 
        StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() 
            @Override
            public void onResponse(String response) 
                callback.onSuccess(response);
            
        , new Response.ErrorListener() 
            @Override
            public void onErrorResponse(VolleyError error) 
                callback.onFailure(error.toString());
            
        );
        mQueue.add(stringRequest);
    

    @Override
    public void get(String url, Map<String, Object> params, HttpCallback callback) 

    

6、全局上下文初始化

package lwl.tianyao.httpproject;

import android.app.Application;

public class MyApplication extends Application 

    @Override
    public void onCreate() 
        super.onCreate();
        //HttpHelper.init(new VolleyProcessor(this));
        //HttpHelper.init(new XUtilsProcessor(this));
        HttpHelper.init(new OkHttpProcessor());
    
7、Activity页面请求
package lwl.tianyao.httpproject;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Map;

public class MyActivity extends Activity 

    String url = "http://v.juhe.cn/weather/index";
    Map<String,Object> params = new HashMap<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        params.put("cityname","长沙");
        params.put("key","123456");

    

    public void click(View view)

        HttpHelper.obtain().post(url, params, new HttpCallback<ResultBean>()

            @Override
            public void onSuccess(ResultBean resultBean) 
                Toast.makeText(MyActivity.this,resultBean.getReason(),Toast.LENGTH_SHORT).show();
            
        );
    

8、其他网络框架

package lwl.tianyao.httpproject;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.Map;

public class XUtilsProcessor implements IHttpProcessor

    public XUtilsProcessor(MyApplication app)
        x.Ext.init(app);
    

    @Override
    public void post(String url, Map<String, Object> params, final HttpCallback callback) 
        RequestParams requestParams  = new RequestParams(url);
        x.http().post(requestParams, new Callback.CommonCallback<String>() 
            @Override
            public void onSuccess(String result) 
                callback.onSuccess(result);
            

            @Override
            public void onError(Throwable ex, boolean isOnCallback) 
                callback.onFailure(ex.getMessage());
            

            @Override
            public void onCancelled(CancelledException cex) 

            

            @Override
            public void onFinished() 

            
        );
    

    @Override
    public void get(String url, Map<String, Object> params, HttpCallback callback) 

    

package lwl.tianyao.httpproject;

import android.os.Handler;

import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpProcessor implements IHttpProcessor

    private OkHttpClient mOkHttpClient;
    private Handler myHandler =null;

    public OkHttpProcessor()
        mOkHttpClient= new OkHttpClient();
        myHandler= new Handler();
    

    @Override
    public void post(String url, Map<String, Object> params, final HttpCallback callback) 
        final RequestBody requestBody = appendBody(params);
        Request request = new Request.Builder()
                            .url(url)
                            .post(requestBody)
                            .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() 
            @Override
            public void onFailure(Call call, IOException e) 
                callback.onFailure(e.getMessage().toString());
            

            @Override
            public void onResponse(Call call, Response response) throws IOException 
                if(response.isSuccessful())
                    final String result = response.body().string();
                    myHandler.post(new Runnable() 
                        @Override
                        public void run() 
                            callback.onSuccess(result);
                        
                    );
                else 
                    final String result = response.body().string();
                    myHandler.post(new Runnable() 
                        @Override
                        public void run() 
                            callback.onFailure(result);
                        
                    );
                
            
        );
    

    private RequestBody appendBody(Map<String,Object> params)
        FormBody.Builder body = new FormBody.Builder();
        if(params==null || params.isEmpty())
            return body.build();
        
        for(Map.Entry<String,Object> entry:params.entrySet())
            body.add(entry.getKey(),entry.getValue().toString());
        
        return body.build();
    

    @Override
    public void get(String url, Map<String, Object> params, HttpCallback callback) 

    

源码: 下载链接

以上是关于动脑学院-网络请求框架的主要内容,如果未能解决你的问题,请参考以下文章

动脑学院-自适应屏幕布局

jmeter 入门--001--动脑学院

动脑学院Android VIP课程_架构_01

(精品网课资源分享)动脑学院VIP50W年薪安卓Android架构性能优化UI/NDK/Flutter

Python在信息工程学院有啥作用?

Python网络爬虫实战案例之:7000本电子书下载