1.导包:
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'//Retrofit2所需要的包
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'//ConverterFactory的Gson依赖包
compile 'com.squareup.retrofit2:converter-scalars:2.0.0-beta4'//ConverterFactory的String依赖包
2.Retrofit需要定义一个接口,用来返回我们的Call对象:
public interface GetRequest_Interface { @GET("toutiao/index?type=top&key=dbedecbcd1899c9785b95cc2d17131c5 ") Call<Bean> getCall(); @FormUrlEncoded @POST("toutiao/index") Call<Bean> postCall(@Field("key") String key, @Field("type") String type); @GET("toutiao/index?type=top&key=dbedecbcd1899c9785b95cc2d17131c5 ") Call<String> getStringCall(); }3. Retrofit对象来进行请求:
//get请求 /* Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://v.juhe.cn/") //设置网络请求的Url地址 .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器 .build(); GetRequest_Interface getRequest_interface = retrofit.create(GetRequest_Interface.class); Call<Bean> call = getRequest_interface.getCall(); call.enqueue(new Callback<Bean>() { @Override public void onResponse(Call<Bean> call, Response<Bean> response) { Bean body = response.body(); } @Override public void onFailure(Call<Bean> call, Throwable t) { } });*/ //post请求 /*Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://v.juhe.cn/") .addConverterFactory(GsonConverterFactory.create()) .build(); GetRequest_Interface getRequest_interface = retrofit.create(GetRequest_Interface.class); Call<Bean> beanCall = getRequest_interface.postCall("dbedecbcd1899c9785b95cc2d17131c5", "top"); beanCall.enqueue(new Callback<Bean>() { @Override public void onResponse(Call<Bean> call, Response<Bean> response) { Bean body = response.body(); System.out.println(body.toString()); } @Override public void onFailure(Call<Bean> call, Throwable t) { } });*/ //String类型请求 Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://v.juhe.cn/") .addConverterFactory(ScalarsConverterFactory.create())//设置数据解析器 .build(); GetRequest_Interface getRequest_interface = retrofit.create(GetRequest_Interface.class); Call<String> stringCall = getRequest_interface.getStringCall(); stringCall.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { System.out.println(response.body()); } @Override public void onFailure(Call<String> call, Throwable t) { } });