如何使用retrofit去请求网络

引入:

compile 'com.google.code.gson:gson:2.8.0'
compile 'com.squareup.retrofit2:retrofit:2.4.0'
compile 'com.squareup.retrofit2:converter-gson:2.4.0'

因为retrofit已经包含了okhttp的库,所以就不要额外引入okhttp了

我们使用retrofit来请求:http://139.199.89.89/api/v1/books这样一个API

private void useRetrofit() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://139.199.89.89") //设置网络请求的Url地址
.addConverterFactory(GsonConverterFactory.create()) //设置数据解析器
.build();
BookService service = retrofit.create(BookService.class);
Call call = service.getResult();

//3.发送请求
call.enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) {
        Log.d(TAG,"<<<< call, Throwable t) {

    }
});

}

我们要写一个service,叫BookService:

package com.pic.optimize.http;

import retrofit2.Call;
import retrofit2.http.GET;

public interface BookService {
@GET("/api/v1/books")
Call getResult();
}

然后要写json的解析实体BookResponse:

import java.util.ArrayList;

public class BookResponse {
public ArrayList data;
public int status;
public String message;
}

然后就在onResponse中就可以得到回调了

我们再写一个添加一本书的post的请求,url是http://139.199.89.89,服务端接收参数是

bookName和bookDescription:

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface BookPostService {
@POST("/api/v1/books")
@FormUrlEncoded
Call getResult(@Field("bookName") String name, @Field("bookDescription") String description);
}

private void useRetrofit() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://139.199.89.89") //设置网络请求的Url地址
.addConverterFactory(GsonConverterFactory.create()) //设置数据解析器
.build();
BookPostService service = retrofit.create(BookPostService.class);
Call call = service.getResult(mBookNameEdit.getText().toString(),mDescriptionEdit.getText().toString());

//3.发送请求
call.enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) {
        Log.d(TAG,"<<<< call, Throwable t) {

    }
});

}

你可能感兴趣的:(如何使用retrofit去请求网络)