Retrofit基础(get/post请求,上传图片,注册)

权限:



 

导入依赖:

    compile 'com.squareup.retrofit2:retrofit:2.0.1'
    compile 'com.squareup.okio:okio:1.5.0'
    compile 'com.squareup.okhttp3:okhttp:3.2.0'
    compile 'com.squareup.retrofit2:converter-gson:2.0.1'
    compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'

public class Api {
    //无参
    public  final static  String baseUrl1 ="http://service.meiyinkeqiu.com/";
    //有参 /
    public  final static  String baseUrl2 ="https://api.github.com/";
    //有参 ?&
    public  final static  String baseUrl3 ="http://www.93.gov.cn/93app/";
    //健值对 字符串
  //  public  final static  String baseUrl4 ="http://120.27.23.105/user/";
    public  final static  String baseUrl4 ="https://www.zhaoapi.cn/user/";
    //上传图片
 //   public  final static  String baseUrl5 ="http://169.254.249.24:8080/";
    public  final static  String baseUrl5 ="http://120.27.23.105/";
}

/**
 * 1. 类的用途 网络接口
 * 2. @author forever
 * 3. @date 2017/11/1 14:32
 */

public interface ApiService {
    /**
     * 无参get请求
     * http://service.meiyinkeqiu.com/service/ads/cptj
     *
     * @return
     */
    @GET("service/ads/cptj")
    Call getNoParams();


    /**
     * 有参get请求
     * 拼接参数 /形式
     *
     * @return https://api.github.com/users/baiiu
     */
    @GET("users/{user}")
   Call getHasParams(@Path("user") String user);


    /**
     * http://www.93.gov.cn/93app/data.do
     * channelId
     * startNum
     * 拼接 ? &
     * 为主
     */
    @GET("data.do")


   Call getHasParams2(@Query("channelId")int channelId, @Query("startNum") int startNum );


    /**
     * post请求 http://120.27.23.105/user/reg 注册
     */
    @POST("reg")
    @FormUrlEncoded//支持表单提交
    Call register(@Field("mobile")String mobile,@Field("password")String password);


    /**
     * 上传图片 参数只有一个 File
     * @param
     * @param file
     * @return
     */
    @Multipart
    @POST("08web/FileUploadServlet")
  Call  uploadPic( @Part MultipartBody.Part file);
    /**
     * 上传图片 参数有2个 uid  file
     * @param
     * @param file
     * @return
     */
    @Multipart
    @POST("file/upload")
  Call  uploadPic2(@Part("uid")RequestBody uid, @Part MultipartBody.Part file);
}

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
     //   getNoParams();
      //  getHasParams();
       // getHasParams2();
       // register();
      //  uploadPic();
       // uploadPic2();
        //addOk();
        retrofitUtils();
    }

    private void retrofitUtils() {
      //  Call call = RetrofitUtils.getInstance().getApiService(Api.baseUrl1, ApiService.class).getNoParams();
        ApiService apiService = RetrofitUtils.getInstance().getApiService(Api.baseUrl1, ApiService.class);
        Call noParams =apiService.getNoParams();
        noParams.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {


            }

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

            }
        });
    }

    private void addOk() {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i("xxx",message);
            }
        });
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).connectTimeout(5000, TimeUnit.SECONDS).build();
        Retrofit retrofit = new Retrofit.Builder().client(okHttpClient).baseUrl(Api.baseUrl1).addConverterFactory(GsonConverterFactory.create()).build();
}

    //上传图片 参数有2个 uid  file
    private void uploadPic2() {
        //创建Retrofit
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Api.baseUrl5).addConverterFactory(GsonConverterFactory.create()).build();
        通过动态代理的方式得到网络接口对象
        ApiService apiService = retrofit.create(ApiService.class);
        //图片文件
        File file = new File(Environment.getExternalStorageDirectory()+"/Pictures/Screenshots/a.jpg");

        //创建RequestBody
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/otcet-stream"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
        String uids = "123";//动态获取
        RequestBody uid = RequestBody.create(MediaType.parse("multipart/form-data"), uids);
        Call call = apiService.uploadPic2(uid, body);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
            }

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

            }
        });

    }
//上传图片 参数只有一个 File
    private void uploadPic() {
        //创建Retrofit
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Api.baseUrl5).addConverterFactory(GsonConverterFactory.create()).build();
        通过动态代理的方式得到网络接口对象
        ApiService apiService = retrofit.create(ApiService.class);
        //图片文件
        File file = new File(Environment.getExternalStorageDirectory()+"/Pictures/Screenshots/a.jpg");

        //创建RequestBody
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/otcet-stream"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
        Call userCall = apiService.uploadPic(body);
        userCall.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
            }

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

            }
        });
    }


    //post请求
    private void register() {
        //创建Retrofit
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Api.baseUrl4).addConverterFactory(GsonConverterFactory.create()).build();
        通过动态代理的方式得到网络接口对象
        ApiService apiService = retrofit.create(ApiService.class);
        Call call = apiService.register("13511237846", "123456");
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                Toast.makeText(MainActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
            }

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

            }
        });

    }

    //有参get请求
    private void getHasParams2() {
        //创建Retrofit
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Api.baseUrl3).addConverterFactory(GsonConverterFactory.create()).build();
        通过动态代理的方式得到网络接口对象
        ApiService apiService = retrofit.create(ApiService.class);
        Call call = apiService.getHasParams2(0, 0);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                Party party = response.body();
                String result = party.getResult();
                Log.i("xxx",result);
            }

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

            }
        });

    }

    //有参get请求
    private void getHasParams() {
        //创建Retrofit
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Api.baseUrl2).addConverterFactory(GsonConverterFactory.create()).build();
        通过动态代理的方式得到网络接口对象
        ApiService apiService = retrofit.create(ApiService.class);
        Call call = apiService.getHasParams("forever");
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                User user = response.body();
                String avatar_url = user.getAvatar_url();
                Log.i("xxx",avatar_url);
            }

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

            }
        });

    }

    //无参get请求
    private void getNoParams() {
        //创建Retrofit
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Api.baseUrl1).addConverterFactory(GsonConverterFactory.create()).build();
        //通过动态代理的方式得到网络接口对象
        ApiService apiService = retrofit.create(ApiService.class);
        //得到Call对象
        Call call = apiService.getNoParams();
        //执行异步请求 回调在主线程
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                News news = response.body();
                List ads = news.getAds();
                for (int i = 0; i < ads.size(); i++) {
                    News.AdsBean adsBean = ads.get(i);
                    Log.i("xxx",adsBean.getGonggaoren());
                }

            }

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

            }
        });

    }
}

你可能感兴趣的:(Retrofit基础(get/post请求,上传图片,注册))