---恢復內容開始---android
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ImageView view = (ImageView) findViewById(R.id.image); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://www.baidu.com/?tn=62095104_19_oem_dg") .build(); BlogService service = retrofit.create(BlogService.class); Call<ResponseBody> call = service.getBlog(2); //用法和OkHttp的call一模一樣,不一樣的是,Android系統中回調方法執行在主線程 call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { System.out.println(response.body().string()); System.out.println(response.code() + " " + response.isSuccessful());//200 true } catch (IOException e) { e.printStackTrace(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { t.printStackTrace(); } }); } public interface BlogService { @GET("blog/{id}")/*這裏的{id} 表示是一個變量*/ Call<ResponseBody> getBlog(@Path("id") int id); } }
retrofit框架是對OKhttp的包裝,爲了簡化代碼邏輯和代碼調用,不一樣於Volley,retrofit更偏向大型持久的數據鏈接,相似於httpurlconnection.retrofit使用註解的方式調用方法,內置了不少註解,好比@get表示使用get請求,能夠看看這個連接的分享https://blog.csdn.net/qiang_xi/article/details/53959437 框架
<uses-permission android:name="android.permission.INTERNET" />
還有依賴:
implementation 'com.squareup.okhttp3:okhttp:4.0.0-RC1'
implementation 'com.squareup.okio:okio:2.2.2'
implementation 'com.squareup.retrofit2:converter-gson:2.6.0'
---恢復內容結束---ide