首先我们在使用的时候需要根据接口返回的数据进行封装javabean对象,便于后面使用。
构建RetrofitService类进行传参和请求方式设置
package cn.hnshangyu.retrofitandrxjava.retrofit;
import java.util.List;
import java.util.Map;
import cn.hnshangyu.retrofitandrxjava.bean.BookResponse;
import cn.hnshangyu.retrofitandrxjava.bean.Parameters;
import cn.hnshangyu.retrofitandrxjava.bean.PostBean;
import cn.hnshangyu.retrofitandrxjava.bean.QueryBean;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.PartMap;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
/**
* 每个接口都需要javaBean对象,需要生成
* Retrofit自动封装
*/
public interface RetrofitService {
/**
* Get方法 @Query
*
* @param name
* @param tag
* @param start
* @param count
* @return
*/
@GET("book/search")
Call<QueryBean> getSearchBooks(@Query("q") String name,
@Query("tag") String tag, @Query("start") int start,
@Query("count") int count);
/**
* Get方法 @QueryMap
*
* @param options
* @return
*/
@GET("book/search")
Call<QueryBean> getSearchBooks(@QueryMap Map<String, String> options);
/**
* Get方法 Query集合
* 一般用不到
* <p>
* 假如你需要添加相同Key值,但是value却有多个的情况,一种方式是添加多个@Query参数,
* 还有一种简便的方式是将所有的value放置在列表中,然后在同一个@Query下完成添加,
* <p>
* 最后得到的url地址为
* <p>
* https://api.douban.com/v2/book/search?q=leadership&q=beyond%20feelings
*
* @param name
* @return
*/
@GET("book/search")
Call<QueryBean> getSearchBooks(@Query("q") List<String> name);
/**
* Get方法 @Path
* <p>
* 此时的url地址为
* <p>
* https://api.douban.com/v2/book/1003078
*
* @param id
* @return
*/
@GET("book/{id}")
Call<BookResponse> getBook(@Path("id") String id);
/**
* Post请求 @field
*
* @param bookId
* @param title
* @param content
* @param rating
* @return
*/
@FormUrlEncoded
@POST("resource/information_list")
Call<PostBean> postSearchBooks(@Field("book") String bookId, @Field("title") String title,
@Field("content") String content, @Field("rating") String rating);
/**
* Post请求 @FieldMap
*
* @param fields
* @return
*/
@FormUrlEncoded
@POST("resource/information_list")
Call<PostBean> postSearchBooks(@FieldMap Map<String, String> fields);
/**
* Post请求 @Body
*
* @param reviews
* @return 错误
* @Body parameters cannot be used with form or multi-part encoding. ???
*/
@POST("resource/information_list")
@Headers({"Content-Type: application/json;charset=UTF-8"})
Call<PostBean> postSearchBooks(@Body Parameters reviews);
/**
* 上传单个文件
*
* @param description
* @param file
* @return
*/
@Multipart
@POST("upload")
Call<ResponseBody> uploadFile(
@Part("description") RequestBody description,
@Part MultipartBody.Part file);
/**
* 上传多个文件方式一
*
* @param description
* @param file1
* @param file2
* @return
*/
@Multipart
@POST("UploadServlet")
Call<ResponseBody> uploadMultipleFiles(
@Part("description") RequestBody description,
@Part MultipartBody.Part file1,
@Part MultipartBody.Part file2);
/**
* 上传多个文件方式二
*
* @param params
* @return
*/
@Multipart
@POST("UploadServlet")
Call<String> uploadFile(@PartMap Map<String, RequestBody> params);
}
封装SYHttpApi构建Retrofit和接口回调
package cn.hnshangyu.retrofitandrxjava.retrofit;
import java.util.Map;
import cn.hnshangyu.retrofitandrxjava.bean.BookResponse;
import cn.hnshangyu.retrofitandrxjava.bean.Parameters;
import cn.hnshangyu.retrofitandrxjava.bean.PostBean;
import cn.hnshangyu.retrofitandrxjava.bean.QueryBean;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by Administrator on 2017/3/23.
* 测试接口
* <p>
* get请求 :https://api.douban.com/v2/movie/top250?start=0&count=10
* <p>
* post请求:http://zhuyu.dashouzhang.org/index.php/app/resource/information_list?app=5
*/
public class SYHttpApi {
private static SYHttpApi mInstance;
private Retrofit retrofit;
private RetrofitService service;
private Call<QueryBean> call;
private Call<BookResponse> bookCall;
private Call<PostBean> stringCall;
private Call<ResponseBody> responseBodyCall;
private Call<String> uploadFile;
public SYHttpApi() {
retrofit = new Retrofit.Builder()
// .baseUrl("https://api.douban.com/v2/")
.baseUrl("http://zhuyu.dashouzhang.org/index.php/app/")
.addConverterFactory(GsonConverterFactory.create())
.build();
service = retrofit.create(RetrofitService.class);
}
public static SYHttpApi getInstance() {
if (mInstance == null) {
synchronized (SYHttpApi.class) {
if (mInstance == null)
mInstance = new SYHttpApi();
}
}
return mInstance;
}
/**
* 取消请求
*/
public void cancelRequest() {
call.cancel();
}
/**
* Get方法 @Query
*
* @param name
* @param tag
* @param start
* @param count
*/
public void getQuerJson(String name, String tag, int start, int count, Callback<QueryBean> callback) {
call = service.getSearchBooks(name, tag, start, count);
call.enqueue(callback);
}
/**
* Get方法 @QueryMap
*
* @param options
* @param callback
*/
public void getQuerMapJson(Map<String, String> options, Callback<QueryBean> callback) {
call = service.getSearchBooks(options);
call.enqueue(callback);
}
/**
* Get方法 @Path
*
* @param id
* @param callback
*/
public void getPath(String id, Callback<BookResponse> callback) {
bookCall = service.getBook(id);
bookCall.enqueue(callback);
}
/**
* Post请求 @field
*
* @param bookId
* @param title
* @param content
* @param rating
* @param callback
*/
public void postQuerJson(String bookId, String title,
String content, String rating, Callback<PostBean> callback) {
stringCall = service.postSearchBooks(bookId, title, content, rating);
stringCall.enqueue(callback);
}
/**
* Post请求 @FieldMap
*
* @param fields
* @param callback
*/
public void postQuerJson(Map<String, String> fields, Callback<PostBean> callback) {
stringCall = service.postSearchBooks(fields);
stringCall.enqueue(callback);
}
/**
* Post请求 @Body
*
* @param parameters
* @param callback
*/
public void postQuerJson(Parameters parameters, Callback<PostBean> callback) {
stringCall = service.postSearchBooks(parameters);
stringCall.enqueue(callback);
}
/**
* 上传单个文件
*
* @param description
* @param file
* @param callback
*/
public void upLoadOneFile(RequestBody description, MultipartBody.Part file,
Callback<ResponseBody> callback) {
responseBodyCall = service.uploadFile(description, file);
responseBodyCall.enqueue(callback);
}
/**
* 上传多个文件方式一
*
* @param description
* @param file
* @param file1
* @param callback
*/
public void upLoadMoreFile(RequestBody description, MultipartBody.Part file,
MultipartBody.Part file1,
Callback<ResponseBody> callback) {
responseBodyCall = service.uploadMultipleFiles(description, file, file1);
responseBodyCall.enqueue(callback);
}
/**
* 上传多个文件方式二
*
* @param params
* @param callback
*/
public void upLoadMoreFile(Map<String, RequestBody> params, Callback<String> callback) {
uploadFile = service.uploadFile(params);
uploadFile.enqueue(callback);
}
}
在OnlyUseRetrofitActivity中进行调用
package cn.hnshangyu.retrofitandrxjava;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import butterknife.Bind;
import butterknife.ButterKnife;
import cn.hnshangyu.retrofitandrxjava.bean.BookResponse;
import cn.hnshangyu.retrofitandrxjava.bean.Parameters;
import cn.hnshangyu.retrofitandrxjava.bean.PostBean;
import cn.hnshangyu.retrofitandrxjava.bean.QueryBean;
import cn.hnshangyu.retrofitandrxjava.retrofit.SYHttpApi;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* 只使用Retrofit
*/
public class OnlyUseRetrofitActivity extends AppCompatActivity {
@Bind(R.id.listview)
ListView listview;
private Context mContext;
private CopyOnWriteArrayList<String> strings = new CopyOnWriteArrayList<>();
private HashMap<String, String> options;
private HashMap<String, String> map;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_only_use_retrofit);
mContext = this;
ButterKnife.bind(this);
initData();
initListener();
}
private void initData() {
strings.add("Get方法 @Query ");
strings.add("Get方法 @QueryMap ");
strings.add("Get方法 Query集合 ");
strings.add("Get方法 Query非必填 ");
strings.add("Get方法 @Path ");
strings.add("Post请求 @field ");
strings.add("Post请求 @FieldMap ");
strings.add("Post请求 @Body ");
strings.add(" 上传单个文件 ");
strings.add(" 上传多个文件方式一 ");
strings.add(" 上传多个文件方式二 ");
listview.setAdapter(new myAdapter());
}
private void initListener() {
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
switch (position) {
case 0://Get方法 @Query
getQuery();
break;
case 1://Get方法 @QueryMap
getQueryMap();
break;
case 2://Get方法 Query集合
Toast.makeText(mContext, "请看RetrofitService类", Toast.LENGTH_LONG).show();
break;
case 3://Get方法 Query非必填
getQueryNoNeed();
break;
case 4://Get方法 @Path
getPath();
break;
case 5://Post请求 @field
postField();
break;
case 6://Post请求 @FieldMap
postFieldMap();
break;
case 7://Post请求 @Body
postBody();
break;
case 8://上传单个文件
Toast.makeText(mContext, "虚拟服务器地址,请查看代码", Toast.LENGTH_LONG).show();
//upDataOneFile();
break;
case 9://上传多个文件方式一
Toast.makeText(mContext, "虚拟服务器地址,请查看代码", Toast.LENGTH_LONG).show();
// upDataMoreFile();
break;
case 10://上传多个文件方式二
Toast.makeText(mContext, "虚拟服务器地址,请查看代码", Toast.LENGTH_LONG).show();
//upLoadMoreFile();
break;
}
}
});
}
/**
* Get方法 @Query
*/
private void getQuery() {
SYHttpApi.getInstance().getQuerJson("小王子", "huang", 0, 3, new Callback<QueryBean>() {
@Override
public void onResponse(Call<QueryBean> call, Response<QueryBean> response) {
Log.e("huangxiaoguo", response.body().getCount() + "");
List<QueryBean.BooksBean> books = response.body().getBooks();
for (int i = 0; i < books.size(); i++) {
Log.e("huangxiaoguo", books.get(i).getSummary());
}
}
@Override
public void onFailure(Call<QueryBean> call, Throwable t) {
Log.e("huangxiaoguo", t.getMessage());
}
});
}
/**
* Get方法 @QueryMap
* 这里map对应的值不能穿null,实践证明访问失败
*/
private void getQueryMap() {
options = new HashMap<>();
options.put("q", "小王子");
options.put("tag", "");
options.put("start", "0");
options.put("count", "3");
SYHttpApi.getInstance().getQuerMapJson(options, new Callback<QueryBean>() {
@Override
public void onResponse(Call<QueryBean> call, Response<QueryBean> response) {
Log.e("huangxiaoguo", response.body().getCount() + "");
List<QueryBean.BooksBean> books = response.body().getBooks();
for (int i = 0; i < books.size(); i++) {
Log.e("huangxiaoguo", books.get(i).getIsbn13());
}
}
@Override
public void onFailure(Call<QueryBean> call, Throwable t) {
Log.e("huangxiaoguo", t.getMessage());
}
});
}
/**
* Get方法 @Query非必填
*/
private void getQueryNoNeed() {
SYHttpApi.getInstance().getQuerJson("小王子", null, 0, 3, new Callback<QueryBean>() {
@Override
public void onResponse(Call<QueryBean> call, Response<QueryBean> response) {
Log.e("huangxiaoguo", response.body().getCount() + "");
List<QueryBean.BooksBean> books = response.body().getBooks();
for (int i = 0; i < books.size(); i++) {
Log.e("huangxiaoguo", books.get(i).getAuthor() + "");
}
}
@Override
public void onFailure(Call<QueryBean> call, Throwable t) {
Log.e("huangxiaoguo", t.getMessage());
}
});
}
/**
* Get方法 @Path
*/
private void getPath() {
SYHttpApi.getInstance().getPath("1003078", new Callback<BookResponse>() {
@Override
public void onResponse(Call<BookResponse> call, Response<BookResponse> response) {
Log.e("huangxiaoguo", response.body().getId() + "");
BookResponse.RatingBean rating = response.body().getRating();
Log.e("huangxiaoguo", rating.getAverage() + "");
}
@Override
public void onFailure(Call<BookResponse> call, Throwable t) {
Log.e("huangxiaoguo", t.getMessage());
}
});
}
/**
* Post请求 @field
*/
private void postField() {
SYHttpApi.getInstance().postQuerJson("12212", "4646546", "dhad", "asa", new Callback<PostBean>() {
@Override
public void onResponse(Call<PostBean> call, Response<PostBean> response) {
List<PostBean.InfoBean> info = response.body().getInfo();
for (int i = 0; i < info.size(); i++) {
Log.e("huangxiaoguo", info.get(i).getInfo());
}
}
@Override
public void onFailure(Call<PostBean> call, Throwable t) {
Log.e("huangxiaoguo", t.getMessage());
}
});
}
/**
* Post请求 @FieldMap
*/
private void postFieldMap() {
map = new HashMap<>();
map.put("bookId", "12212");
map.put("title", "4646546");
map.put("content", "dhad");
map.put("rating", "asa");
SYHttpApi.getInstance().postQuerJson(map, new Callback<PostBean>() {
@Override
public void onResponse(Call<PostBean> call, Response<PostBean> response) {
List<PostBean.InfoBean> info = response.body().getInfo();
for (int i = 0; i < info.size(); i++) {
Log.e("huangxiaoguo", info.get(i).getContent());
}
}
@Override
public void onFailure(Call<PostBean> call, Throwable t) {
Log.e("huangxiaoguo", t.getMessage());
}
});
}
/**
* Post请求 @Body
*/
private void postBody() {
Parameters parameters = new Parameters();
parameters.bookId = "12212";
parameters.content = "dhad";
parameters.rating = "asa";
parameters.title = "4646546";
SYHttpApi.getInstance().postQuerJson(parameters, new Callback<PostBean>() {
@Override
public void onResponse(Call<PostBean> call, Response<PostBean> response) {
List<PostBean.InfoBean> info = response.body().getInfo();
for (int i = 0; i < info.size(); i++) {
Log.e("huangxiaoguo", info.get(i).getCreate_time());
}
}
@Override
public void onFailure(Call<PostBean> call, Throwable t) {
}
});
}
/**
* 上传单个文件
* multipart/form-data表示将数据以二进制的形式传入服务端中的request中,
* <p>
* MultipartBody.Part.createFormData("aFile", file.getName(), requestFile);
* <p>
* 中第一个参数是数组名,第二个参数是文件名;将每条数据都必须封住到RequestBody中。
* 如果你以一下方式创建上传文件:
* <p>
* String filePath = Environment.getExternalStorageDirectory()+File.separator+"love.txt";
* File file = new File(filePath);
*/
private void upDataOneFile() {
//访问手机端的文件资源,保证手机端sdcdrd中必须有这个文件
File file = new File("/sdcard/Pictures/myPicture/index.jpg");
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("aFile", file.getName(), requestFile);
// 添加其他的part
String descriptionString = "This is a description";
RequestBody description =
RequestBody.create(MediaType.parse("multipart/form-data"), descriptionString);
SYHttpApi.getInstance().upLoadOneFile(description, body, new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.e("huangxiaoguo", "success");
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
}
/**
* 上传多个文件方式一
*/
private void upDataMoreFile() {
//访问手机端的文件资源,保证手机端sdcdrd中必须有这个文件
File file = new File("/sdcard/Pictures/myPicture/index.jpg");
File file1 = new File("/sdcard/Picuures/myPicture/me.txt");
RequestBody requestFile =
RequestBody.create(MediaType.parse("applicaiton/otcet-stream"), file);
RequestBody requestFile1 =
RequestBody.create(MediaType.parse("applicaiton/otcet-stream"), file1);
MultipartBody.Part body1 =
MultipartBody.Part.createFormData("aFile", file.getName(), requestFile);
MultipartBody.Part body2 =
MultipartBody.Part.createFormData("aFile", file.getName(), requestFile1);
// 添加其他的part
String descriptionString = "This is a description";
RequestBody description =
RequestBody.create(MediaType.parse("multipart/form-data"), descriptionString);
SYHttpApi.getInstance().upLoadMoreFile(description, body1, body2, new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.e("huangxiaoguo", "success");
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
}
/**
* 上传多个文件方式二
*/
private void upLoadMoreFile() {
File file = new File("/sdcard/Pictures/myPicture/index.jpg");
File file1 = new File("/sdcard/Picuures/myPicture/me.txt");
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
RequestBody requestBody1 = RequestBody.create(MediaType.parse("multipart/form-data"), file1);
Map<String, RequestBody> params = new HashMap<>();
params.put("file\"; filename=\"" + file.getName(), requestBody);
params.put("file\"; filename=\"" + file1.getName(), requestBody1);
SYHttpApi.getInstance().upLoadMoreFile(params, new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
Log.e("huangxiaoguo", response.body().toString());
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("huangxiaoguo", t.getMessage());
}
});
}
private class myAdapter extends BaseAdapter {
@Override
public int getCount() {
return strings.size();
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
View inflate;
ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
inflate = View.inflate(mContext, R.layout.textview, null);
holder.mText = (TextView) inflate.findViewById(R.id.text);
inflate.setTag(holder);
} else {
inflate = view;
holder = (ViewHolder) inflate.getTag();
}
holder.mText.setText(strings.get(position));
return inflate;
}
}
class ViewHolder {
TextView mText;
}
}
源码下载 : http://download.csdn.net/detail/huangxiaoguo1/9792052
网友评论