# 與 Android Retroft 2 的相遇(Android Retrofit 2 in Java) > 小弟我目前就讀於某私立大學資工系(不出意外的話今年會畢業),平常在學校就會自學一些App,某次接API的時候,終於受不了了Volley每次API Response都要一層一層用JsonObject解下去的痛苦(或許是我真的不會寫)_(┐ ◟;゚д゚)ノ > > 所以寫畢業專題之際就順手研究了一些Rx,然而在寫的時候轉念一想既然都要用Rx了不然連架構也換成MVVM,最後就整個Rebuild了 (☍﹏⁰) ## 前言 這篇文章主要是要做為一個Retrofit以及MVVM新手紀錄當下心得的概念,本篇會著重介紹Retrofit 2 在 Java 上的應用方式,之後如果有時間的話應該還會寫一篇關於 MVVM 使用心得,本篇文章如有謬誤海請各位先進多多海涵 (っ・Д・)っ ## 應用技術 - Retrofit2 - MVVM - Json - Gson - Java Thread - RxJava - Live Data ## 小工具 > 這是網路上找到 Json to Gson 小工具推薦給大家 [jsonschema2pojo](http://www.jsonschema2pojo.org/) > 當然Android studio 的plugin也可以用(不過我每次使用都錯誤就沒有用了....)  ## 開發環境(build.gradle) 在gradle 中加入這兩行 ```xmls= dependencies { //retrofit2 implementation 'com.squareup.retrofit2:retrofit:2.3.0' implementation 'com.squareup.retrofit2:converter-gson:2.5.0' ... } ``` ## 進入正題~實作Retrofit 2 ### First step - 在Manitfest中加入網路權限 ```xml= <uses-permission android:name="android.permission.INTERNET" /> ``` - 啊~突然想到 若是URL不是https的話需要在xml package中新增一個network_security_config檔案,不然會出現“Error! Network is not available”的錯誤 Manifest內容如下⬇️ ```xml= <application android:networkSecurityConfig="@xml/network_security_config"> </application> ``` network_security_config內容如下⬇️ ```xml= <network-security-config xmlns:android="http://schemas.android.com/apk/res/android"> <base-config cleartextTrafficPermitted="true" /> </network-security-config> ``` ### Second step - 先來一個最基礎的Json試試 ```json= { "data": { "a": "256", "b": "180", "c": "33", "d": "80" } } ``` 然後用一開始提到的小工具轉成Gson ```java= import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class APIResponse { @SerializedName("data") @Expose private APIResponseInData data; public APIResponseInData getData() { return data; } public void setData(APIResponseInData data) { this.data = data; } } ``` ```java= import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class APIResponseInData { @SerializedName("a") @Expose private int a; @SerializedName("b") @Expose private int b; @SerializedName("c") @Expose private int c; @SerializedName("d") @Expose private int d; public int getRankA() { return a; } public int getRankB() { return b; } public int getRankC() { return c; } public int getRankD() { return d; } } ``` ### Third step
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up