Retrofit Study notes

### what is Retrofit framework

  • The Retrofit framework is a popular web request framework from Square that is efficient and simple to implement. Using annotations and dynamic proxies, greatly simplifies the tedious steps of network requests, very suitable for handling restful web requests, #### features
  • Good performance, fast processing, easy to use. One of the most popular HTTP Client libraries for Android today (faster than Volley)
  • Using the REST API is very convenient
  • Support for NIO (new IO API, alternative to standard Java IO API)
  • Retrofit processes network requests using OKHttp by default
  • GSON parsing is used by default

Common annotation interface for Network access in Retrofit2

  • @get GET Network request mode
  • @pSOt Indicates the PSOT network request mode
  • @headers information parameter
  • @path Path parameters. Replace the parts of the URL included by “{” and “}”
  • @query Query parameter, which appends a string like “page=1” to the address URL to form the request parameter to be submitted to the server
  • @queryMap Query parameter set. Appends a string like “type=text&count=30&page=1” to the URL address
  • @formurlencoded The content in a form field to avoid garbled characters
  • @field specifies the name and value of each space in the form Field
  • FieldMap Collection of form fields
  • @multipart Post To submit a block request. If a file is uploaded, Multipart must be specified
  • @part POST Submits a block request
  • @body POST Submit a chunking request ###Retrofit2 code implementation steps #### Five steps
  • 1. Define an interface (encapsulating URL addresses and data requests)
  • 2. Instantiate Retrofit
  • 3. Create interface service objects using Retrofit instances
  • 4. The interface service object invokes the methods in the interface to obtain the Call object
  • 5. Call objects perform requests (asynchronous, synchronous) ### GET Interface methods in network requests
  • 1, GET request, method has no parameter
@GET("article/list/latest? page")
Call<ResponseBody> getLatestString();
Copy the code
  • The @path and @query parameters are specified in the GET request. @path is used to replace parts of the URL containing “{” and “}”. @query appends a string like “page=1” to the URL to form a request parameter to submit to the server
@GET("article/list/{type}?")
Call<QiushiModel> getLatesList(@Path("type")) String type,@Query("page") int page);
Copy the code
  • 3. GET request, submit form data, define @queryMap parameter in method. The @queryMap argument appends a string like “type=text*count=308&page=1” to the URL
@GET ("MyWeb/RegServlet")
Call<ResponseBody> getKeyValuePair(@QueryMap Map<String,String> map);
Copy the code
  • BaseUrl will be ignored in this case. BaseUrl will be ignored in this case
@GET("http://img.234g.com/userup/112/12.jpg")
Call<ResponseBody> getNetWorkData();
Copy the code

### Simply use (without Rx) ##### base address

 public final static String BASE_URL = "http://m2.qiushibaike.com/";
Copy the code

##### Interface method

    @GET("article/list/latest? page=1")
    Call<ResponseBody> getLatestJsonString();
Copy the code

##### Create a factory for the interface

public class ServerFactory {

    public static <T> T createServiceFactory(final Class<T> serverClass, String url) {

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(10, TimeUnit.SECONDS);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        returnretrofit.create(serverClass); }}Copy the code

##### Request for data

 private void initData() { MyServerInterface serverInterface = ServerFactory.createServiceFactory(MyServerInterface.class, Constant.BASE_URL);  Call<ResponseBody> call = serverInterface.getLatestJsonString(); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> Response) {// I: -------ThreadId------>"yinlei"."-------ThreadId------>" + Thread.currentThread().getId());
                if (response.isSuccess()) {
                    String result = null;
                    try {
                        result = response.body().string();
                        try {
                            JSONObject resultObject = new JSONObject(result);
                            int errCode = resultObject.getInt("err");
                            if (errCode == 0) {
                                JSONArray items = resultObject.getJSONArray("items");
                                // Toast.makeText(MainActivity.this, items.toString(), Toast.LENGTH_SHORT).show();
                                for (int i = 0; i < items.length(); i++) {
                                    PageBean.ItemsBean item = new Gson().fromJson(items.getString(i), new TypeToken<PageBean.ItemsBean>() {
                                    }.getType());
                                    mItemsBeen.add(item);
                                }
                            }
                            mTvResult.setText(result);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }
Copy the code

##### The result is a JSON string

http://m2.qiushibaike.com/article/list/latest?page=1 (if you want to see the results, can open the link)Copy the code

Request data using RxJava+Retrofit #####URL address

public final static String USER_URL = "https://api.github.com";
Copy the code

##### Interface method

// GET personal information @get ("/users/JakeWharton")
    Observable<User> getUserDataObservable();
Copy the code

##### returns the factory class for the interface

public class ServerFactoryObserver {

    public static <T> T createServiceFactory(final Class<T> serverClass, String url) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(10, TimeUnit.SECONDS);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(builder.build())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        returnretrofit.create(serverClass); }}Copy the code

##### Data request

 MyServerInterface serverInterface = ServerFactoryObserver.createServiceFactory(MyServerInterface.class, Constant.USER_URL);
        serverInterface.getUserDataObservable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<User>() {
                    @Override
                    public void onCompleted() {
                        mDialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(User user) {
                        Log.d("UserActivity", user.toString()); updateUi(user); }});Copy the code

##### Small problem description

// It is possible to load the url from the web page, but it is possible to load the url from the web page. String conver_url = muser.getavatar_URL (); Picasso.with(this).load("http://pic29.nipic.com/20130508/9252150_163600489317_2.jpg").placeholder(R.mipmap.ic_launcher)
                    .into(mIvConver);
Copy the code

##### demo (there seems to be a problem with my AS, all the character encoding is already UTF-8, but there is a message that I have encoding error (not before))

# # # # # # making address: https://github.com/wuyinlei/RetrofitDemo Here is simply to use the retrofit, later to simple encapsulation of retrofit, join the Rx. That’s all for today.