Retrofit获取网络数据

来源:互联网 发布:京东和淘宝的竞品分析 编辑:程序博客网 时间:2024/06/09 12:17
首先需要导依赖
    compile 'com.squareup.retrofit2:retrofit:2.0.2'    compile 'com.squareup.okhttp3:okhttp:3.9.0'    compile 'com.squareup.retrofit2:converter-gson:2.3.0'

实现注解的接口
package com.bwie.retrofit;import java.util.Map;import okhttp3.ResponseBody;import retrofit2.Call;import retrofit2.http.FieldMap;import retrofit2.http.FormUrlEncoded;import retrofit2.http.POST;public interface APIInterface {    /**     * https://api.github.com/users/Guolei1130     接口定义;注解方式添加请求方式;get请求内部放拼接的连接和需要传递的参数;     后面是/拼接的     返回对象     *///        @GET("users/{username}")//        Call getLogin(@Path("username")String user);    /**     * 返回ResponseBody     */    //    @GET("users/{username}")    //    CallgetLoginInfo(@Path("username")String user);    /**     * get请求  拼接参数     */    //        @GET("ting?method=baidu.ting.billboard.billList&type=1&size=10")    //        Call getLoginInfo();    /**     * get请求  使用Query拼接参数     */    //    @GET("ting?method=baidu.ting.billboard.billList")    //    Call getLoginInfo(@Query("type") String type , @Query("size") String haha);    /**     * post请求  拼接参数     */    //    @POST("ting?method=baidu.ting.billboard.billList&type=1&size=10")    //    Call getLoginInfo();    /**     * post请求  使用Query拼接参数     *///        @POST("ting?method=baidu.ting.billboard.billList")//        Call getLoginInfo(@Query("type") String type , @Query("size") String haha);    /**     * post请求  使用Field表单形式拼接参数     */    //    @POST("ting?method=baidu.ting.billboard.billList")    //    @FormUrlEncoded    //    Call getLoginInfo(@Field("type") String type , @Field("size") String haha);    /**     * post请求  使用FieldMap集合形式拼接参数     */        @POST("ting?method=baidu.ting.billboard.billList&type=1")        @FormUrlEncoded        CallgetLogin(@FieldMap Map map);    /**     * Http请求  可以在里面修改请求的方法,拼接的参数     */    //    @HTTP(method = "GET",path ="ting?method=baidu.ting.billboard.billList&type=1&size=10",hasBody = false)    //    CallgetLoginInfo();}

网络拦截器
import android.os.Build;import java.io.IOException;import okhttp3.Interceptor;import okhttp3.Request;import okhttp3.Response;/** * 网络拦截器 */public class LoggingInterceptor implements Interceptor {    private static final String UA = "User-Agent";    @Override    public Response intercept(Chain chain) throws IOException {        Request request = chain.request()                .newBuilder()                .addHeader(UA, makeUA())                .build();        return chain.proceed(request);    }    private String makeUA() {        String s = Build.BRAND + "/" + Build.MODEL + "/" + Build.VERSION.RELEASE;        return Build.BRAND + "/" + Build.MODEL + "/" + Build.VERSION.RELEASE;    }}

主要代码
package com.bwie.retrofit;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.util.Log;import java.io.IOException;import java.util.HashMap;import java.util.Map;import okhttp3.OkHttpClient;import okhttp3.ResponseBody;import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;import retrofit2.Retrofit;import retrofit2.converter.gson.GsonConverterFactory;public class MainActivity extends AppCompatActivity {    String url = "http://tingapi.ting.baidu.com/v1/restserver/";    String url1 = "https://api.github.com";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        /**         * 如果要加拦截器等关于OKhttp的东西,就需要创建OkHttpClient实例         */        OkHttpClient client = new OkHttpClient.Builder()                .addInterceptor(new LoggingInterceptor()).build();        Retrofit retrofit = new Retrofit.Builder()                .baseUrl(url)                .client(client)                .addConverterFactory(GsonConverterFactory.create())                .build();                        APIInterface apiInterface = retrofit.create(APIInterface.class);                Map map = new HashMap<>();        //        ?method=baidu.ting.billboard.billList&type=1&size=10//                map.put("aaa","type=1");                map.put("bbb","size=10");                Call call = apiInterface.getLogin(map);//                Call call = apiInterface.getLoginInfo("10","1");                call.enqueue(new Callback() {                    @Override                    public void onResponse(Call call, Response response) {//                        Toast.makeText(MainActivity.this, response.body().getSong_list().get(1).getTitle(), Toast.LENGTH_SHORT).show();                        try {                            Log.i("TAG",response.body().string());                        } catch (IOException e) {                            e.printStackTrace();                        }                        Log.e("TAG", "成功");                    }                    @Override                    public void onFailure(Call call, Throwable t) {                        Log.e("TAG", "错误");                    }                });//        APIInterface apiInterface = retrofit.create(APIInterface.class);//获取请求接口实例;//        Call call = apiInterface.getLogin("Guolei1130");//        call.enqueue(new Callback() {//            @Override//            public void onResponse(Call call, Response response) {//                Log.e("TEST", Thread.currentThread().getName());//                Log.e("TEST", response.body().toString());//                Toast.makeText(MainActivity.this, response.body().toString(), Toast.LENGTH_SHORT).show();//            }////            @Override//            public void onFailure(Call call, Throwable t) {////            }//        });        //        //        Call call = apiInterface.getLoginInfo("Guolei1130");        //        call.enqueue(new Callback() {        //            @Override        //            public void onResponse(Call call, Response response) {        //                try {        //                    Log.e("TEST", response.body().string());        //                } catch (IOException e) {        //                    e.printStackTrace();        //                }        //            }        //        //            @Override        //            public void onFailure(Call call, Throwable t) {        //        //            }        //        });        //同步请求,必须在子线程;        //Response  =call.execute();    }}



阅读全文
0 0
原创粉丝点击