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

权限:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

导入依赖:

    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<News> getNoParams();


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


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


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


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


    /**
     * 上传图片 参数只有一个 File
     * @param
     * @param file
     * @return
     */
    @Multipart
    @POST("08web/FileUploadServlet")
  Call<User>  uploadPic( @Part MultipartBody.Part file);
    /**
     * 上传图片 参数有2个 uid  file
     * @param
     * @param file
     * @return
     */
    @Multipart
    @POST("file/upload")
  Call<User>  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<News> call = RetrofitUtils.getInstance().getApiService(Api.baseUrl1, ApiService.class).getNoParams();
        ApiService apiService = RetrofitUtils.getInstance().getApiService(Api.baseUrl1, ApiService.class);
        Call<News> noParams =apiService.getNoParams();
        noParams.enqueue(new Callback<News>() {
            @Override
            public void onResponse(Call<News> call, Response<News> response) {


            }

            @Override
            public void onFailure(Call<News> 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<User> call = apiService.uploadPic2(uid, body);
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<User> 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<User> userCall = apiService.uploadPic(body);
        userCall.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<User> 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<User> call = apiService.register("13511237846", "123456");
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                Toast.makeText(MainActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<User> 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<Party> call = apiService.getHasParams2(0, 0);
        call.enqueue(new Callback<Party>() {
            @Override
            public void onResponse(Call<Party> call, Response<Party> response) {
                Party party = response.body();
                String result = party.getResult();
                Log.i("xxx",result);
            }

            @Override
            public void onFailure(Call<Party> 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<User> call = apiService.getHasParams("forever");
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                User user = response.body();
                String avatar_url = user.getAvatar_url();
                Log.i("xxx",avatar_url);
            }

            @Override
            public void onFailure(Call<User> 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<News> call = apiService.getNoParams();
        //执行异步请求 回调在主线程
        call.enqueue(new Callback<News>() {
            @Override
            public void onResponse(Call<News> call, Response<News> response) {
                News news = response.body();
                List<News.AdsBean> 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<News> call, Throwable t) {

            }
        });

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值