关于只使用retrofit2.0进行网络请求的demo:http://blog.csdn.net/shb2058/article/details/71404615
1.导入必要的包,主要在导retrofit适配rxjava包的时候需要注意,这里的适配是rxjava2而不是rxjava,否则报依赖包重复错误
/*retrofit的引入*/
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
/*retrofit对rx支持的引入*/
compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
/*rx的引入*/
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.0.9'
2.retrofit网络请求时的接口建立(传递json过去的)
//基于rxjava的登录
@Headers({"Content-Type:application/json;charset=utf-8", "Accept:application/json;"})
@POST("json/reply/AgencyLoginRequest")
Observable postLoginByAx(@Body RequestBody route);
实现
/*retrofit和rxjava一起使用的请求*/
private void loginByRxAndRetrofit(){
Map map = new HashMap<>();
map.put("Phone", "15888888888");
map.put("Password", CommonUtils.encodeMD5("123456").toUpperCase());
map.put("AccountId", "");
map.put("WxOpenId", "");
map.put("Source", "3");
map.put("Timestamp", CommonUtils.getUTC());
map.put("IpAddress", "");
map.put("MachineNo", "123456");
Retrofit retrofit=new Retrofit.Builder().baseUrl(BaseHttp.Base_url)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
HttpApiS httpApiS = retrofit.create(HttpApiS.class);
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), CommonUtils.convertPostJson(map));
httpApiS.postLoginByAx(requestBody)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer() {
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onNext(@NonNull LoginBean loginBean) {
if (loginBean.getIsSuccess() == 1) {
Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "登录失败", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(@NonNull Throwable e) {
}
@Override
public void onComplete() {
}
});
}
3.传递键值对过去的post/get
@GET("XCAPI/GetProList")
Observable GetProList(@QueryMap Map params);
@FormUrlEncoded
@POST("/call.aspx?forward=02-0201&caller=M")
Observable getAllUsers(@FieldMap Map params);
private void loginByAX() {
Map map = new HashMap<>();
map.put("USER_ACC1", "stud1");
map.put("USER_PWD1", "111111");
Retrofit retrofit = new Retrofit.Builder().baseUrl(BaseUrl.BaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
HttpApiS httpApiS = retrofit.create(HttpApiS.class);
httpApiS.getAllUsers(map).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer() {
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onNext(@NonNull LoginBean loginBean) {
if (loginBean.getReturnCode().equals("1")) {
Log.e("登陆成功", "登录cheongsam");
} else {
Log.e("登录失败", "登录失败===");
}
}
@Override
public void onError(@NonNull Throwable e) {
Log.e("登录错误", e.getMessage() + "'");
}
@Override
public void onComplete() {
}
});
}
4.传文件、文件和数据一起穿
//图片和参数一起上传
@Multipart
@POST("XCAPI/PostarticleFile")
Observable postFiles1(@PartMap Map map
,@Part List partList);
@Multipart
@POST("XCAPI/PostImgs")
Observable uploadImageNew(@Part List partList);
Map params = new HashMap<>();
params.put("data", RequestBody.create(MediaType.parse("application/json; charset=utf-8"), GsonUtil.getInstance().toJson(yeKuoBean)));
MultipartBody.Builder builder = new MultipartBody.Builder()
.setType(MultipartBody.FORM);
for (ImageBean fileBean : allFile) {
File path = new File(fileBean.getPath());
RequestBody imageBody1 = RequestBody.create(MediaType.parse("multipart/form-data"), path);
builder.addFormDataPart(fileBean.getFileName(), fileBean.getFileName(), imageBody1);
}
List parts = builder.build().parts();
//params,
getRetrofitInterface().upYKtoServer(params, parts).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer() {
private void upImage(final CollectBean collectBean) {
if (collectBean.getHadUped() == 2) {
Log.e("图片已经上传了", "====");
//表示已经上传
// handler_Updata.sendEmptyMessage(UpImageOk);
return;
}
final int id = collectBean.getId();
File image_path = new File(collectBean.getF_bjImg());//表的tu
File image_jinx = new File(collectBean.getF_jhximg());//进户线
MultipartBody.Builder builder = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("pid", "1");//表单类型
RequestBody imageBody1 = RequestBody.create(MediaType.parse("multipart/form-data"), image_path);
RequestBody imageBody2 = RequestBody.create(MediaType.parse("multipart/form-data"), image_jinx);
builder.addFormDataPart("f_bjImg", image_path.getName(), imageBody1);
builder.addFormDataPart("f_jhximg", image_path.getName(), imageBody2);
List parts = builder.build().parts();
getRetrofitInterface().uploadImageNew(parts).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer() {
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onNext(@NonNull NewUpImageBean newUpImageBean) {
Log.e("upimage", "onnext");
if (newUpImageBean.getStatu() == 1) {
ContentValues contentValues = new ContentValues();
contentValues.put("hadUped", "2");
DataSupport.updateAsync(CollectBean.class, contentValues, id).listen(new UpdateOrDeleteCallback() {
@Override
public void onFinish(int rowsAffected) {
if (rowsAffected == 1) {
//handler_Updata.sendEmptyMessage(UpImageOk);
} else {
// handler_Updata.sendEmptyMessage(UpImageFail);
// error_message = "写入本地数据库出错!";
}
}
});
} else {
// handler_Updata.sendEmptyMessage(UpImageFail);
// error_message = newUpImageBean.getMsg();
}
}
@Override
public void onError(@NonNull Throwable e) {
// handler_Updata.sendEmptyMessage(UpImageFail);
// error_message = e.getMessage();
}
@Override
public void onComplete() {
}
});
}