1. 程式人生 > >Retrofit 2.0框架使用。

Retrofit 2.0框架使用。

工作中發現我們的程式碼裡面使用的retrofit1.9,在前人搭建好的架構下使用起來真的得心應手。真的要給前人一個大大的贊。
良心,不能只是在填坑的時候噴前人,優秀的程式碼還是要學習的。

既然Retrofit已經升級到2.0了,那就學習使用下2.0的Retrofit吧。

首先說明一下我們要做些什麼。
目標:伺服器介面提供資料,移動端請求接收資料,對資料處理

說明:需求涉及到網路請求,最好不要在主執行緒。

實現:
1:後臺介面資料型別:

1、介面地址:http://xxxxxxx    GET
2、介面引數:無。
3、返回結果:[{"id":1,"name":"名稱"
},{"id":1,"name":"名稱"}]

2:定義資料物件取名為 Ind

package com.example.root.myapplication.test;

/**
 * Created by root on 16-11-28.
 */

public class Ind{
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }


    public
String getName() { return name; } public void setName(String name) { this.name = name; } }

3.定義介面

package com.example.root.myapplication.test;


import java.util.ArrayList;

import retrofit.Call;
import retrofit.http.GET;
import rx.Observable;

/**
 * Created by root on 16-11-28.
 */
public interface IndApi { @GET("/ind/api/list") Call<ArrayList<Ind>> getInds(); }

4.建立service。我們在service裡面獲取介面資料。首先建立一個baseService把一些通用的方法整理進來,這裡簡單的一個sendMessage方法。
TestBaseService

package com.example.root.myapplication.test;

import android.app.IntentService;
import android.content.Intent;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;

/**
 * Created by root on 16-11-28.
 */

public class TestBaseService extends IntentService {

    public TestBaseService(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if(intent == null){
            return;
        }
    }

    protected void sendMessage(Messenger messenger,Object obj){
        if(null != obj){
            Message msg = Message.obtain();
            msg.obj = obj;

            try {
                messenger.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }
}

再定義關於Ind的service

package com.example.root.myapplication.test;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Messenger;
import android.util.Log;

import java.util.ArrayList;

import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;

/**
 * Created by root on 16-11-28.
 */

public class IndService extends TestBaseService {
    private static final String ACTION_GET_INDS = "get_inds";
    private static final String MESSENGER = "MESSENGER";


    Retrofit retrofit ;
    public IndService() {
        super("IndService");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        String baseUrl = "https://xxxxxxxx.com/";  //這裡是我們公司後臺介面不方便給出

        retrofit = new Retrofit.Builder().baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public static void startGetInds(Context context,Messenger messenger){
        Intent intent = new Intent(context,IndService.class);
        intent.setAction(ACTION_GET_INDS);
        intent.putExtra(MESSENGER,messenger);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if(null == intent) return;
        final String action = intent.getAction();
        Bundle bundle = intent.getExtras();
        if(ACTION_GET_INDS.equals(action)){
            getInds(bundle);
        }
    }



    public void getInds(Bundle bundle){

        final Messenger messenger = (Messenger) bundle.get(MESSENGER);

        IndApi service = retrofit.create(IndApi.class);
        service.getInds().enqueue(new Callback<ArrayList<Ind>>() {
            @Override
            public void onResponse(Response<ArrayList<Ind>> response, Retrofit retrofit) {
                if (response.body() != null) {
                    ArrayList<Ind> inds = response.body();
                    sendMessage(messenger,inds);
                }
            }

            @Override
            public void onFailure(Throwable t) {
                sendMessage(messenger,t);
            }
        });
    }
}

這樣就可以獲取到介面資料了。在需要使用的地方呼叫IndService.startGetInds()就可以了。
示例:

package com.example.root.myapplication;

import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.example.root.myapplication.test.Ind;
import com.example.root.myapplication.test.IndService;

import java.util.ArrayList;

/**
 * Created by root on 16-11-28.
 */

public class MainActivity extends AppCompatActivity {


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

        getInds();

    }

    private void getInds() {
        IndService.startGetInds(MainActivity.this, new Messenger(mHandler));
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Log.i("mzy", "i handle the message");
            ArrayList<Ind> ins = (ArrayList<Ind>) msg.obj;
            for (Ind i : ins) {
                Log.i("mzy", "inds == " + i.getName());
            }
        }
    };
}

就此伺服器的資料就載入到了移動端了。資料任你擺佈。

相關推薦

Retrofit 2.0框架使用

工作中發現我們的程式碼裡面使用的retrofit1.9,在前人搭建好的架構下使用起來真的得心應手。真的要給前人一個大大的贊。 良心,不能只是在填坑的時候噴前人,優秀的程式碼還是要學習的。 既然Retrofit已經升級到2.0了,那就學習使用下2.0的

Android Retrofit 2.0框架上傳圖片解決方案(一張與多張的處理)

1.單張圖片的上傳 /** * 上傳一張圖片 * @param description * @param imgs * @return */ @Mul

Retrofit 2.0基於OKHttp更高效更快的網絡框架 以及自定義轉換器

讀取數據 index gson final resp adapter oid 簡單的 build 時間關系,本文就 Retrofit 2.0的簡單使用 做講解 至於原理以後有空再去分析 項目全面、簡單、易懂 地址: 關於Retrofit 2.0的簡單使用如下: htt

Retrofit 2.0使用詳解,配合OkHttp、Gson,Android最強網路請求框架

1.使用retrofit,需要下載一些jar包 2.介紹這些jar包的作用 在1.x版本的retrofit框架: 只需要Retrofit包和gson-2.4.jar包就行了,那時的Retrofit預設是使用okhttp jar包來網路請

RESTful,Retrofit 2.0 使用教程

art rest blog 使用 data- 教程 AS detail rom RESTful風格 https://baike.sogou.com/v73300762.htm?fromTitle=RESTful Retrofit 2.0 使用教程 https://blog.

IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0框架學習保護API

IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0框架學習之保護API。 使用IdentityServer4 來實現使用客戶端憑據保護ASP.NET Core Web API 訪問。 IdentityServer4 GitHub: https://g

Android:手把手帶你 深入讀懂 Retrofit 2.0 原始碼

前言 在Android開發中,網路請求十分常用 而在Android網路請求庫中,Retrofit是當下最熱的一個網路請求庫 Github截圖 今天,我將手把手帶你深入剖析Retrofit v2.0的原始碼,希望你們會喜歡 請儘量在PC端

Android Retrofit 2.0 的詳細 使用攻略(含例項講解)

前言 在Andrroid開發中,網路請求十分常用 而在Android網路請求庫中,Retrofit是當下最熱的一個網路請求庫 Github截圖 今天,我將獻上一份非常詳細Retrofit v2.0的使用教程,希望你們會喜歡。 目錄 目錄 1. 簡介

Retrofit 2.0 詳細教程

詳細的 Retrofit 2.0 使用教程(含例項講解) 轉載自:Carson_Ho https://blog.csdn.net/carson_ho/article/details/73732076 前言 在Andrroid開發中,網路請求十分常用 而在Andr

Retrofit 2.0: The biggest update yet on the best HTTP Client Library for Android

Retrofit is one of the most popular HTTP Client Library for Android as a result of its simplicity and its great performance compare to th

Android Retrofit 2.0(二)使用教程OkHttp3 + Gson + RxJava

系列文章推薦:相關資料新增依賴compile 'com.squareup.okhttp3:okhttp:3.3.1' compile 'com.squareup.retrofit2:retrofit:2.1.0'別忘在Manifest裡新增許可權<uses-permis

這是一份很詳細的 Retrofit 2.0 使用教程(含例項講解)

前言 在Andrroid開發中,網路請求十分常用 而在Android網路請求庫中,Retrofit是當下最熱的一個網路請求庫 今天,我將獻上一份非常詳細Retrofit v2.0的使用教程,希望你們會喜歡。 目錄 1. 簡介

Retrofit 2.0 GET 請求引數出現錯誤

目前使用的是Retrofit 2.0.2測試版本 因為GEI請求中出現 {} ’錯誤符號(具體也沒看是哪個符號錯誤)出現not valid as a java.net.URI導致無法訪問, 解決辦法 Call<RootList> ge

Android Retrofit 2.0使用——轉載吳小龍同學http://wuxiaolong.me/2016/01/15/retrofit/

這幾天學習Retrofit 看到一篇非常好的文章如下: 原網址為:http://wuxiaolong.me/2016/01/15/retrofit/感謝吳小龍同學的默默奉獻。 例項帶你瞭解Retrofit 2.0的使用,分享目前開發Retrofit遇到的坑和心得。 新

Quick and easy guide to Retrofit 2.0 setup or migration with RxJava

Quick and easy guide to Retrofit 2.0 setup or migration with RxJavaYou might have noticed that the final Retrofit 2.0 is out, so what better moment to upgr

Retrofit 2.0檔案上傳

使用Retrofit進行檔案上傳,肯定離不開Part & PartMap。 public interface FileUploadService { @Multipart @POST("upload") Call<

Retrofit 2.0全部註解及注意事項

文章目錄 一.導圖 二.請求方法類 1.除@HTTP外其他7個: [email protected] 三.引數類 1.Headers 2.Header 3.Body 4.

Retrofit 2.0 自定義Converter

requestBodyConverter 不執行的解決辦法: 引數要使用@Body這種形式,否則 request 方法會不起作用。 在Retrofit中,無論是傳送資料和接收資料,都是通過OKHttp的RequestBody和ResponseBody來實現的

Android Retrofit 2.0自定義Converter(JSONObject Converter)

如果在使用的過程中,不需要Gson以及其他轉換器,只是單純的返回 JSONObject,那這樣怎麼處理呢? 通過閱讀原始碼發現,可以通過自定義轉換器的方式操作: import retro

Retrofit 2.0 常用寫法示例

由於Retrofit的官方文件實在是很難理解,我這裡收集了一些常見的寫法,供在實際使用中參考。 對URL的處理 BASEURL 通常我們在定義retrofit的時候,會設定一個baseurl。 Retrofit.Builder builder