Skip to content

Commit

Permalink
-支持多拦截器
Browse files Browse the repository at this point in the history
-支持multipart数组上传
  • Loading branch information
tohodog committed Dec 19, 2019
1 parent 5429439 commit 83d536c
Show file tree
Hide file tree
Showing 10 changed files with 102 additions and 43 deletions.
5 changes: 4 additions & 1 deletion app/src/main/java/com/song/demo/AppContext.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ public void onCreate() {

private void init() {

QSHttp.init(QSHttpConfig.Build(this).interceptor(new QSInterceptor()).build());
QSHttp.init(QSHttpConfig.Build(this)
.interceptor(new QSInterceptor())
.interceptor(new QSInterceptor2())
.build());

}

Expand Down
12 changes: 8 additions & 4 deletions app/src/main/java/com/song/demo/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ protected void onCreate(Bundle savedInstanceState) {
downGET(url);
upLoad(url);

// parserJson();
parserJson();

}

Expand Down Expand Up @@ -150,7 +150,10 @@ public void upLoad(String url) {

.param("bytes", new byte[1024])//multipart方式上传一个字节数组
.param("file", new File(getExternalCacheDir(), "http.txt"))//multipart方式上传一个文件
.multipartBody("img", "image/*", "x.jpg", new byte[1024])

//IdentityHashMap支持重复key,需new
.multipartBody(new String("img"), "image/*", "qs.jpg", new byte[1024])
.multipartBody(new String("img"), "image/*", "qs.jpg", new byte[1024])

.buildAndExecute(new ProgressCallback() {
@Override
Expand Down Expand Up @@ -192,7 +195,7 @@ public void onComplete(User<User> dataUser) {
});

QSHttp.postJSON("https://api.reol.top/test/json")
.header("string", "{\"status\":0,\"data\":3.6}")
.jsonBody("3.666489")
.buildAndExecute(new MyHttpCallback<Double>() {
@Override
public void onComplete(Double dataUser) {
Expand Down Expand Up @@ -221,7 +224,8 @@ public void onComplete(User dataUser) {
});

QSHttp.postJSON("https://api.reol.top/test/json")
.header("string", "3.6")
.header("row", "row")
.jsonBody("3.6")
.buildAndExecute(new QSHttpCallback<String>() {
@Override
public void onComplete(String dataUser) {
Expand Down
34 changes: 34 additions & 0 deletions app/src/main/java/com/song/demo/QSInterceptor2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.song.demo;

import org.song.http.framework.HttpException;
import org.song.http.framework.Interceptor;
import org.song.http.framework.RequestParams;
import org.song.http.framework.ResponseParams;

/**
* Created by song
* Contact github.com/tohodog
* Date 2019/12/18
* 多拦截器
*/
public class QSInterceptor2 implements Interceptor {
@Override
public ResponseParams intercept(Chain chain) throws HttpException {

String url = chain.request().url();
if (url != null && !url.startsWith("http")) {
url = API.HOST + url;
}

RequestParams newRequestParams = chain.request()
.newBuild(url)
.header("Interceptor2", "Interceptor2")
//继续添加修改其他
.build();


ResponseParams responseParams = chain.proceed(newRequestParams);
//请求结果参数如有需要也可以进行修改
return responseParams;
}
}
4 changes: 2 additions & 2 deletions qshttp/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ android {
minSdkVersion 9
targetSdkVersion
compileSdkVersion 28
versionCode 11
versionName "1.4.3"
versionCode 12
versionName "1.5.0"
}
buildTypes {
release {
Expand Down
3 changes: 1 addition & 2 deletions qshttp/src/main/java/org/song/http/QSHttp.java
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,9 @@ public static RequestParams.Builder upload(String url) {
return postMulti(url);
}

//这里可以添加公共参数鉴权

private static RequestParams.Builder build(String url, HttpEnum.RequestMethod requestMethod) {
return RequestParams.Build(url)
.requestMethod(requestMethod);
//.header("sessionKey", "sessionKey");
}
}
4 changes: 2 additions & 2 deletions qshttp/src/main/java/org/song/http/framework/Interceptor.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ public interface Interceptor {
ResponseParams intercept(Chain chain) throws HttpException;

interface Chain {
RequestParams request();
RequestParams request();//请求参数

ResponseParams proceed(RequestParams request) throws HttpException;
ResponseParams proceed(RequestParams request) throws HttpException;//流程继续
}
}
51 changes: 30 additions & 21 deletions qshttp/src/main/java/org/song/http/framework/QSHttpClient.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package org.song.http.framework;


import java.util.Random;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
Expand All @@ -21,12 +21,13 @@ public class QSHttpClient {

private ExecutorService executorService;

private Interceptor interceptor;
private List<Interceptor> interceptorList;


public QSHttpClient(IHttpTask iHttpTask, QSHttpConfig qsHttpConfig) {
this.iHttpTask = iHttpTask;
this.qsHttpConfig = qsHttpConfig;
interceptor = qsHttpConfig.interceptor();
interceptorList = qsHttpConfig.interceptorList();
executorService = Executors.newFixedThreadPool(qsHttpConfig.poolSize());
}

Expand All @@ -50,24 +51,10 @@ public void run() {
ResponseParams response;
final HttpProgress hp = isProgress ? new HttpProgress(mThreadWhat) : null;
try {
if (interceptor != null) {//拦截器
response = interceptor.intercept(new Interceptor.Chain() {
@Override
public RequestParams request() {
return _request;
}

@Override
public ResponseParams proceed(RequestParams request) throws HttpException {
_request = request;
return access(request, hp);
}
});
if (response == null) {
throw HttpException.Custom(interceptor.getClass().getName() + ".intercept() - return value can't null!");
}
} else
response = access(_request, hp);
//拦截器
response = runInterceptor(0, _request, hp);
//经过拦截器,request被改变了
_request = response.requestParams();
response.setSuccess(true);
} catch (Exception e) {
e.printStackTrace();
Expand Down Expand Up @@ -97,6 +84,28 @@ public ResponseParams proceed(RequestParams request) throws HttpException {
return mThreadWhat;
}

//递归调用拦截器
private ResponseParams runInterceptor(final int index, final RequestParams request, final HttpProgress hp) throws HttpException {
if (interceptorList == null || index >= interceptorList.size()) {//递归终点
ResponseParams response = access(request, hp);
response.setRequestParams(request);
return response;
}

Interceptor interceptor = interceptorList.get(index);
return interceptor.intercept(new Interceptor.Chain() {
@Override
public RequestParams request() {
return request;
}

@Override
public ResponseParams proceed(RequestParams request) throws HttpException {
return runInterceptor(index + 1, request, hp);//递归调用
}
});
}

//具体联网逻辑 保证返回ResponseParams对象不为null
private ResponseParams access(final RequestParams request, final HttpProgress hp) throws HttpException {
ResponseParams response = null;
Expand Down
16 changes: 10 additions & 6 deletions qshttp/src/main/java/org/song/http/framework/QSHttpConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

import android.app.Application;

import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSocketFactory;

Expand All @@ -16,7 +19,7 @@ public class QSHttpConfig {
private Application application;
private HttpEnum.XX_Http xxHttp;

private Interceptor interceptor;
private List<Interceptor> interceptorList;

private SSLSocketFactory sslSocketFactory;
private String[] sslHost;
Expand Down Expand Up @@ -46,8 +49,8 @@ public HttpEnum.XX_Http xxHttp() {
return xxHttp;
}

public Interceptor interceptor() {
return interceptor;
public List<Interceptor> interceptorList() {
return interceptorList;
}

public String[] sslHost() {
Expand Down Expand Up @@ -102,7 +105,7 @@ public static final class Builder {
private HttpEnum.XX_Http xxHttp = HttpEnum.XX_Http.OK_HTTP;//
private String cachePath;

private Interceptor interceptor;
private List<Interceptor> interceptorList;

private SSLSocketFactory sslSocketFactory;
private String[] sslHost;
Expand All @@ -122,7 +125,7 @@ private Builder(Application application) {
public QSHttpConfig build() {
QSHttpConfig qsHttpConfig = new QSHttpConfig();
qsHttpConfig.debug = debug;
qsHttpConfig.interceptor = interceptor;
qsHttpConfig.interceptorList = interceptorList;
qsHttpConfig.application = application;
qsHttpConfig.xxHttp = xxHttp;
qsHttpConfig.poolSize = poolSize;
Expand Down Expand Up @@ -154,7 +157,8 @@ public Builder xxHttp(HttpEnum.XX_Http xxHttp) {
}

public Builder interceptor(Interceptor interceptor) {
this.interceptor = interceptor;
if (this.interceptorList == null) this.interceptorList = new ArrayList<>();
this.interceptorList.add(interceptor);
return this;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

Expand Down Expand Up @@ -445,9 +446,10 @@ public RequestParams.Builder jsonBody(Object object) {
String json = "{}";
if (object instanceof org.json.JSONObject) {
json = object.toString();
} else {
} else if (!(object instanceof CharSequence)) {
json = JSON.toJSONString(object);
}
} else
json = String.valueOf(object);
requestBody(HttpEnum.CONTENT_TYPE_JSON_ + charset, json);
return this;
}
Expand Down Expand Up @@ -478,7 +480,7 @@ public RequestParams.Builder toMultiBody(String multipartType) {
toMultiBodyFlag = true;
this.multipartType = multipartType;
if (multipartBody == null)
multipartBody = new HashMap<>();
multipartBody = new IdentityHashMap<>();//支持重复key,内存地址要不一样
bodyType = 2;
return this;
}
Expand All @@ -488,6 +490,7 @@ public RequestParams.Builder toMultiBody(String multipartType) {
*/
public RequestParams.Builder multipartBody(String key, String contentType, String filename, Object value) {
toMultiBody();
//new String(key)才能保证不同地址,key不重复
multipartBody.put(key, new RequestBody(contentType, filename, value));
return this;
}
Expand Down
7 changes: 5 additions & 2 deletions qshttp/src/main/java/org/song/http/framework/Utils.java
Original file line number Diff line number Diff line change
Expand Up @@ -248,8 +248,11 @@ public static boolean checkNet() {
}

public static void showToast(String str) {
if (QSHttpManage.application != null && str != null)
Toast.makeText(QSHttpManage.application, str, Toast.LENGTH_LONG).show();
if (QSHttpManage.application != null && str != null) {
Toast toast = Toast.makeText(QSHttpManage.application, str, Toast.LENGTH_LONG);
toast.setText(str);
toast.show();
}
}


Expand Down

0 comments on commit 83d536c

Please sign in to comment.