添加依赖:
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/";
}
定义ApiService接口:
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) {
}
});
}
}
网络请求封装的工具类:
public class RetrofitUtils {
private static RetrofitUtils retrofitUtils;
private RetrofitUtils(){
}
//双重检验锁
public static RetrofitUtils getInstance(){
if (retrofitUtils==null){
synchronized (RetrofitUtils.class){
if (retrofitUtils==null){
retrofitUtils = new RetrofitUtils();
}
}
}
return retrofitUtils;
}
private static Retrofit retrofit;
//封装创建Retrofit
public static synchronized Retrofit getRetrofit(String url){
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();
if (retrofit==null){
retrofit = new Retrofit.Builder().client(okHttpClient).baseUrl(url).addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
//此方法为了返回网络接口对象
public <T>T getApiService(String url,Class<T> cl){
Retrofit retrofit = getRetrofit(url);
return retrofit.create(cl);
}
}