• Android自定义的http网络框架


    Android自定义的http网络框架

      为什么要自定义网络框架:

          Android项目中,40%以上会涉及到与后台的http网络。通常的项目都会

      用第三方的网络框架。第三方的网络框架存在扩展性低,兼容性等问题。

         

      自定义http网络框架的优点:高性能、高扩展、兼容性好。

        

      下面要实现的网络框架的特点:

          1、调用层傻瓜式调用网络请求,用户只需要传入Url,请求参数,所需要请求的类型

          2、支持json、图片、音频请求,可根据业务场景需要进行扩展

          3、回调的结果发生在主线程

       

          4、高性能,支持高并发,请求队列依次获取,可以设置最大并发数

      实现思路:

      http网络请求流程:应用层(Activty)持有IrosonseListeren调用Volley层,Volley根据不同的请求类型(json、图片、音频)生产不同的Httptask,Httptask根据请求类型切换到子线程调用不同的IhttpService,IhttpService持有Ihttplistener进行网络请求和获取inputStream,Ihttplistener解析inputSteam后,切换到主线程,让应用层Activity回调IrosonseListeren获取网络请求返回的值。

          1、应用了生成者消费者模式,应用层(Activity)生成任务,放入请求队列,

          供线程池(threadPool)调用。

          2、应用了策略模式,使得不同的请求实现IhttpService ,选择执行

       json、图片、音频等网络请求和处理,保证了功能的扩展性。

          3、使用了装饰器模式,将请求类型的选择处理逻辑放在了Volley层,使得

       应用层可以傻瓜式调用。

      实现思路图:

      

     

         

      代码实现:

      

      public class MainActivity extends AppCompatActivity {

    private String url="http://114.55.30.161/nms3/mmsWebDeviceThree/getDeviceByOrgans.do";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    }

    public void volleynet(View view){
    TaskParams tp=new TaskParams(url,
    // new String[]{"home_id", ""},
    new String[]{"organId", "15"}

    );
    //json请求
    Volley.sendjsonRequest(tp.getEncodeParams(), tp.getUrl(), new IJsonListener() {

    @Override
    public void onSuccess(String response) {
    Log.e("jjjjjj","userResponse---->"+response.toString());
    Toast.makeText(getApplicationContext(),response.toString(),Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError() {

    }
    });

    //图片请求扩展
    // Volley.sendImgRequest(tp.getEncodeParams(), tp.getUrl(), new IImagListener() {
    //
    // @Override
    // public void onSuccess(String response) {
    //
    // }
    //
    // @Override
    // public void onError() {
    //
    // }
    // });

    //获取音频扩展
    }
    }

       

    public class TaskParams {

    //http://192.168.1.50:4501/IF/SIM/sim_task.aspx?CELL_WIDTH=800&CELL_HEIGHT=480&BOX_SIGNATURE=070457c801902417668&number=2&task_type=0
    private static String CELL_WIDTH="CELL_WIDTH";
    private static String CELL_HEIGHT="CELL_HEIGHT";
    private static String BOX_SIGNATURE="BOX_SIGNATURE";
    private String url;
    private static String NUM = "number";
    private static String TYPE = "task_type";
    private static String USER_ID = "user_id";

    private Map<String, String> params;

    private TaskParams() {
    }

    public TaskParams(String url, int cell_width, int cell_heith, String box_signature, int num, int type) throws ParamsInvaliedException {
    params = new HashMap<String, String>();
    if (url == null) {
    throw new ParamsInvaliedException("task count is invalied");
    } else {
    this.url = url;
    }

    params.put(CELL_WIDTH, String.valueOf(cell_width));
    params.put(CELL_HEIGHT, String.valueOf(cell_heith));
    params.put(BOX_SIGNATURE, box_signature);

    params.put(NUM, String.valueOf(num));

    //params.put(TYPE, String.valueOf(type));

    // params.put(USER_ID, Common.USER_Id);
    }

    public TaskParams(String url, String[]... para){
    params = new HashMap<String, String>();
    this.url = url;
    if(para != null){
    for(int i = 0; i < para.length; i++){
    String[] p = para[i];
    if(p.length != 2){
    continue;
    }
    this.params.put(p[0], p[1]);
    }
    }
    }

    public String getUrl() {
    return url;
    }

    public void setUrl(String url) {
    this.url = url;
    }

    public String getEncodeParams() {
    try {
    StringBuilder encodedString = new StringBuilder();
    boolean first = true;
    for (String key : params.keySet()) {
    String value = params.get(key);
    if (value.equals(""))
    continue;
    if (first)
    first = false;
    else
    encodedString.append("&");
    encodedString.append(URLEncoder.encode(key, "UTF-8")).append("=")
    .append(URLEncoder.encode(value, "UTF-8"));
    }
    return encodedString.toString();
    } catch (UnsupportedEncodingException e) {
    return null;
    }
    }

    public static class ParamsInvaliedException extends Exception {
    private static final long serialVersionUID = 1L;

    public ParamsInvaliedException(String s) {
    super(s);
    }
    }
    }

      

     

          public class Volley {
    //供调用层调用
    public static void sendjsonRequest(String params,
    String url,IJsonListener httpCallable){
    //回调
    IHttpListener httpListener=
    new JSONDealListener(httpCallable);

    //实例化http网络请求线程线程
    HttpTask httpTask=new HttpTask(params,url,httpListener,new JSONHttpSercice());

    ThreadPoolManager.getInstance().execute(new FutureTask<Object>(httpTask,null));


    }

    //图片访问 供扩展用
    // public static void sendImgRequest(String params,
    // String url,IImagListener httpCallable){
    // //回调
    // IHttpListener httpListener=
    // new ImageDealListener(httpCallable);
    //
    // //实例化http网络请求线程线程
    // HttpTask httpTask=new HttpTask(params,url,httpListener);
    //
    // ThreadPoolManager.getInstance().execute(new FutureTask<Object>(httpTask,null));
    //
    //
    // }

    }

    public class HttpTask implements Runnable{
    private IHttpService httpService;
    public HttpTask(String params,
    String url,IHttpListener iHttpListener,IHttpService httpService){
    this.httpService=httpService;
    httpService.setUrl(url);
    httpService.setHttpCallBack(iHttpListener);

    params = params.replace("%40", "@");

    try {
    this.httpService.setRestquestDate(params.getBytes());
    } catch (Exception e) {
    e.printStackTrace();
    }

    }

    @Override
    public void run() {
    //执行网络请求
    this.httpService.excute();
    }
    }

    //处理请求后的回调,是否请求
    // 成功、失败后的操作
    public interface IHttpListener {

    void onSuccess(InputStream inputStream);

    void onError();
    }
     

    //处理网络请求的接口
    public interface IHttpService {
    //请求url
    void setUrl(String url);
    //执行请求,专门处理inputStream
    void excute();
    //设置回调接口
    void setHttpCallBack(IHttpListener iHttpListener);
    //设置请求参数
    void setRestquestDate(byte[] restquestDate);

    }


    //提供调用层使用
    public interface IJsonListener{
    void onSuccess(String response);

    void onError();
    }
     
    //处理JSON相应请求
    public class JSONDealListener implements IHttpListener {

    //请求返回解析后的回调
    private IJsonListener jsonListener;

    //切换到主线程
    Handler handler=new Handler(Looper.getMainLooper());

    public JSONDealListener(IJsonListener jsonListener) {
    this.jsonListener = jsonListener;
    }

    @Override
    public void onSuccess(InputStream inputStream) {
    //解析网络请求的响应流
    final String content=getContent(inputStream);


    //切换到主线程
    handler.post(new Runnable() {
    @Override
    public void run() {
    if(jsonListener!=null){
    //主线程调用
    jsonListener.onSuccess(content);
    }
    }
    });
    }

    //解析响应流
    private String getContent(InputStream inputStream) {
    String content=null;
    try {
    BufferedReader reader=
    new BufferedReader(new InputStreamReader(inputStream));

    StringBuilder sb=new StringBuilder();

    String line=null;

    while((line=reader.readLine())!=null){
    sb.append(line+" ");
    }

    return sb.toString();
    }catch (Exception e){
    System.out.println("Error="+e.toString());
    }finally {
    try {
    inputStream.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    return content;
    }

    @Override
    public void onError() {

    }
    }



    public class JSONHttpSercice implements IHttpService {
    IHttpListener httpListener;
    String url;

    private byte[] requestData;

    @Override
    public void setUrl(String url) {
    this.url = url;
    }

    @Override
    public void setRestquestDate(byte[] restquestDate) {
    this.requestData=restquestDate;
    }

    @Override
    public void excute() {

    HttpURLConnection conn = null;
    OutputStream out = null;
    InputStream in = null;

    try {
    conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod("POST");
    conn.setConnectTimeout(3000);
    conn.setReadTimeout(3000);
    conn.setDoOutput(true);

    out = conn.getOutputStream();

    out.write(requestData);
    out.flush();
    out.close();

    int code = conn.getResponseCode();
    if (code != HttpURLConnection.HTTP_OK) {
    // return null;
    }

    in = conn.getInputStream();

    httpListener.onSuccess(in);
    // String resstr = HttpUtils.changeInputStream2(in);
    } catch (IOException e) {
    e.printStackTrace();
    }



    }

    @Override
    public void setHttpCallBack(IHttpListener iHttpListener) {
    this.httpListener=iHttpListener;
    }


    }
     
    //线程池管理
    public class ThreadPoolManager {
    private static ThreadPoolManager
    instance=new ThreadPoolManager();

    public static ThreadPoolManager getInstance() {
    return instance;
    }

    private ThreadPoolExecutor threadPoolExecutor;

    private LinkedTransferQueue<Future<?>> service=new LinkedTransferQueue<>();

    private ThreadPoolManager(){
    threadPoolExecutor=new ThreadPoolExecutor(4,10,10, TimeUnit.SECONDS,
    new ArrayBlockingQueue<Runnable>(4),handler);
    threadPoolExecutor.execute(runnable);
    }

    private Runnable runnable =new Runnable() {
    @Override
    public void run() {
    FutureTask futureTask=null;

    while (true){
    try {
    futureTask= (FutureTask) service.take();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }

    if(futureTask!=null){
    threadPoolExecutor.execute(futureTask);
    }
    }
    }
    };

    public <T> void execute(FutureTask<T> futureTask){
    if(futureTask!=null){
    try {
    service.put(futureTask);
    }catch (Exception e){
    e.printStackTrace();

    }
    }
    }

    private RejectedExecutionHandler handler=new RejectedExecutionHandler() {
    @Override
    public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) {
    service.put(new FutureTask<Object>(runnable,null));
    }
    };

    }
     

    Github地址:https://git.oschina.net/qpww/myVolley.git
  • 相关阅读:
    Mysql:FAQ:A.5 Triggers
    Mysql:Where are stored {procedures | functions | triggers} ? (例程)存储过程、函数、触发器,存在哪儿?
    Mysql:5.7:all triggers are 【FOR EACH ROW】
    Mysql:FAQ:A.4 Stored Procedures and Functiions
    ANSI SQL 2003:美国国家标准:SQL-2003:该规范并不是free获取——你得花钱!
    Mysql:可恨又可怜Query Cache特性:已死!莫用!
    Mysql:Innodb Cluster【It's not NDB】:Based On Group Replication
    Android -- 补间动画和属性动画
    Android -- Android广播
    Android -- Android数据存储
  • 原文地址:https://www.cnblogs.com/qqpw/p/6636530.html
Copyright © 2020-2023  润新知