项目中使用OkHttp框架的Post请求时一般都是以键值对的形式上传参数 。比如
Map<String, String> params = new HashMap<>();
params.put("receiverId", receiverId);//接收者id
params.put("receiverName", receiverName);//接受者姓名
params.put("sentName", sentName);//发送者姓名
...
mObservable=mRxAndroidOkhttp.post(posturl,params);
但是也有的接口要求以文件的形式上传参数。
String json="{"receiverId":"20365845","receiverName":"张三","sentName":"李四"}";
OkHttp框架也是支持的。
工具类
package com.wjn.viewlistdemo.okhttp.utils;
import com.wjn.viewlistdemo.okhttp.constants.ROConstants;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;
public class RxAndroidOkhttp {
private OkHttpClient mOkHttpClient = null;//OkHttpClient 对象
private static RxAndroidOkhttp mRxAndroidOkhttp = null;//RxAndroidOkhttp 对象
/**
* 构造方法私有化
*/
private RxAndroidOkhttp() {
//创建okhttp对象 以及连接,读,取超时时间
mOkHttpClient = new OkHttpClient.Builder()
.connectTimeout(ROConstants.nettimeout, TimeUnit.SECONDS)//连接时间
.readTimeout(ROConstants.nettimeout, TimeUnit.SECONDS)//读时间
.writeTimeout(ROConstants.nettimeout, TimeUnit.SECONDS)//写时间
.retryOnConnectionFailure(true)//连接失败后是否重新连接
.build();
}
/**
* 获取此单例类对象的方法
*/
public static RxAndroidOkhttp getInstance() {
if (null == mRxAndroidOkhttp) {//单例对象为空
synchronized (RxAndroidOkhttp.class) {
mRxAndroidOkhttp = new RxAndroidOkhttp();
}
}
return mRxAndroidOkhttp;
}
/**
* post请求方法 Json方式提交
*/
public Observable<String> post(final String url, final String json) {
//创建被观察者
Observable<String> observable = Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
final Subscriber mSubscriber = subscriber;
//没有取消订阅的时候
if (!mSubscriber.isUnsubscribed()) {
RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), json);
//构建post请求
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
if (mOkHttpClient != null) {
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//通知订阅者的错误信息
mSubscriber.onError(e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (null != response) {//response 不为空
if (response.isSuccessful()) {//response 请求成功
//通知订阅者的成功信息
mSubscriber.onNext(response.body().string());
} else {//response 请求失败
//通知订阅者的错误信息
IOException IOExceptionx = new IOException();
mSubscriber.onError(IOExceptionx);
}
} else {//response 为空
//通知订阅者的错误信息
IOException IOExceptionx = new IOException();
mSubscriber.onError(IOExceptionx);
}
//通知完毕
mSubscriber.onCompleted();
}
});
}
}
}
});
return observable;
}
}
和普通Post提交方式只修改下面一行
RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), json);
调用
package com.wjn.viewlistdemo.okhttp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.wjn.viewlistdemo.R;
import com.wjn.viewlistdemo.okhttp.utils.RxAndroidOkhttp;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class OkHttpActivity extends AppCompatActivity {
private RxAndroidOkhttp mRxAndroidOkhttp = null;//RxAndroidOkhttp对象
private Observable mObservable = null;
private String json = "{\"receiverId\":\"2035698\",\"receiverName\":\"张三\",\"sentName\":\"李四\"}\n";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_okhttp);
findView();
}
/**
* 初始化各种View
*/
private void findView() {
mRxAndroidOkhttp = RxAndroidOkhttp.getInstance();
getData("", json);
}
/**
* 请求数据
*/
private void getData(final String posturl, String json) {
if ((null != mRxAndroidOkhttp)) {
//observable定义被观察者
mObservable = mRxAndroidOkhttp.post(posturl, json);
if (null != mObservable) {
//定义观察者
Subscriber<String> mSubscriber = new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
}
};
/**
* 订阅者关联被观察者
* Schedulers.io()说明是输入输出的计划任务
* AndroidSchedulers.mainThread()说明订阅者是中ui主线程中执行
* */
mObservable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(mSubscriber);
}
}
}
}