1. 程式人生 > >Retrofit2.0 基本使用

Retrofit2.0 基本使用

相關文章:

Retrofit2.0

// Retrofit庫
    implementation 'com.squareup.retrofit2:retrofit:2.0.2'
    // Okhttp庫
    implementation 'com.squareup.okhttp3:okhttp:3.1.2'

    implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
 <uses-permission android:name="android.permission.INTERNET"/>
package com.example.administrator.rxjavademo;

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

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Field;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.HTTP;
import retrofit2.http.Headers;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.PartMap;
import retrofit2.http.Path;
import retrofit2.http.Query;

public class RetrofitActivity extends AppCompatActivity {

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

//        initView();
        initData();

    }


    private void initView() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://www.apiopen.top/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        // 建立 網路請求介面 的例項
        final GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);
        //對 傳送請求 進行封裝
//        Call<WeatherBeans> call = request.getCall();

        Call<WeatherBeans> call1 = request.getCall1("大同");

        //傳送網路請求(非同步)
        call1.enqueue(new Callback<WeatherBeans>() {
            @Override
            public void onResponse(Call<WeatherBeans> call, Response<WeatherBeans> response) {
                //請求處理 ,輸出結果

                WeatherBeans beans = response.body();

                Log.i("info", "1--" + beans.getData().getYesterday().getDate() + "--" + beans.getData().getYesterday().getHigh());

            }

            @Override
            public void onFailure(Call<WeatherBeans> call, Throwable t) {
                Log.i("info", "請求失敗");
            }
        });


    }

    private void initData() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://xxx.xxx.xxx.xxx:xxx")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        PostRequest_Interface request = retrofit.create(PostRequest_Interface.class);

//        Call<PostLoginBeans> call = request.postLogin1("wangwu","111");

        Map<String,String> map = new HashMap<>();
        map.put("LoginName","wangwu");
        map.put("LoginPass","111");
        Call<PostLoginBeans> call = request.postLogin3(map);

//        //post 提交file檔案
//
//        RequestBody username = RequestBody.create(MediaType.parse(""), "wangwu");
//        RequestBody password = RequestBody.create(MediaType.parse(""), "111");
//
//        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", "test.txt", new RequestBody() {
//        });
//        Call<PostLoginBeans> call3 = request.postLogin2(username, password, filePart);

//        // @PartMap
//        // 實現和上面同樣的效果
//        Map<String, RequestBody> fileUpload2Args = new HashMap<>();
//        fileUpload2Args.put("name", name);
//        fileUpload2Args.put("age", age);
//        //這裡並不會被當成檔案,因為沒有檔名(包含在Content-Disposition請求頭中),但上面的 filePart 有
//        //fileUpload2Args.put("file", file);
//        Call<PostLoginBeans> call4 = service.testFileUpload2(fileUpload2Args, filePart); //單獨處理檔案
//        ResponseBodyPrinter.printResponseBody(call4);







        call.enqueue(new Callback<PostLoginBeans>() {
            @Override
            public void onResponse(Call<PostLoginBeans> call, Response<PostLoginBeans> response) {

                PostLoginBeans postLoginBeans = response.body();
                Log.i("info",postLoginBeans.getData().get(0).getCname());

            }

            @Override
            public void onFailure(Call<PostLoginBeans> call, Throwable t) {

            }
        });

    }
}
    interface PostRequest_Interface{
    //    http://120.76.247.101:836/api/User/UserLogin
        //LoginName  wangwu
        //LoginPass  111

        @POST("/api/User/UserLogin")
        @FormUrlEncoded
        Call<PostLoginBeans> postLogin1(@Field("LoginName") String LoginName
                ,@Field("LoginPass") String pass);

        @POST("/api/User/UserLogin")
        @FormUrlEncoded
        Call<PostLoginBeans> postLogin3(@FieldMap Map<String,String> map);

        //post  提交file檔案
        @POST("/api/User/UserLogin")
        @Multipart
        Call<PostLoginBeans> postLogin2(@Part("LoginName") RequestBody LoginName
                , @Part("LoginPass") RequestBody pass, @Part MultipartBody.Part file);

        @POST("/form")
        @Multipart
        Call<PostLoginBeans> postLogin4(@PartMap Map<String, RequestBody> args);


    }

interface GetRequest_Interface{
    //https://www.apiopen.top/weatherApi?city=大同

    @GET("/weatherApi?city=大同")
    Call<WeatherBeans> getCall();

    @GET("weatherApi?")
    Call<WeatherBeans> getCall1(@Query("city") String city);

    //    @Headers("Authorization: authorization")
    //    @GET("/weatherApi?city=大同")
    //    Call<WeatherBeans> getCall();
}