新增了分类
然后不知道改了啥
This commit is contained in:
1
netlibs/.gitignore
vendored
Normal file
1
netlibs/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/build
|
||||
34
netlibs/build.gradle
Normal file
34
netlibs/build.gradle
Normal file
@@ -0,0 +1,34 @@
|
||||
plugins {
|
||||
id 'com.android.library'
|
||||
}
|
||||
|
||||
android {
|
||||
namespace 'com.yutou.netlibs'
|
||||
compileSdk 34
|
||||
|
||||
defaultConfig {
|
||||
minSdk 28
|
||||
targetSdk 34
|
||||
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
minifyEnabled false
|
||||
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
targetCompatibility JavaVersion.VERSION_1_8
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
|
||||
api 'com.squareup.okhttp3:okhttp:3.14.9'
|
||||
api 'com.squareup.retrofit2:retrofit:2.3.0'
|
||||
api 'com.alibaba.fastjson2:fastjson2:2.0.52'
|
||||
|
||||
}
|
||||
21
netlibs/proguard-rules.pro
vendored
Normal file
21
netlibs/proguard-rules.pro
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# You can control the set of applied configuration files using the
|
||||
# proguardFiles setting in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
||||
6
netlibs/src/main/AndroidManifest.xml
Normal file
6
netlibs/src/main/AndroidManifest.xml
Normal file
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<application />
|
||||
|
||||
</manifest>
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.yutou.netlibs.converter;
|
||||
|
||||
import retrofit2.CallAdapter;
|
||||
import retrofit2.Retrofit;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
public class JsonCallAdapter extends CallAdapter.Factory{
|
||||
public static JsonCallAdapter create(){
|
||||
return new JsonCallAdapter();
|
||||
}
|
||||
@Override
|
||||
public CallAdapter<?, ?> get(Type type, Annotation[] annotations, Retrofit retrofit) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.yutou.netlibs.converter;
|
||||
|
||||
import okhttp3.RequestBody;
|
||||
import okhttp3.ResponseBody;
|
||||
import retrofit2.Converter;
|
||||
import retrofit2.Retrofit;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
public class JsonConverterFactory extends Converter.Factory {
|
||||
public static JsonConverterFactory create() {
|
||||
return new JsonConverterFactory();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
|
||||
// return super.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
|
||||
return new JsonRequestBodyConverter<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
|
||||
// return super.responseBodyConverter(type, annotations, retrofit);
|
||||
return new JsonResponseBodyConverter<>(type);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.yutou.netlibs.converter;
|
||||
|
||||
import okhttp3.MediaType;
|
||||
import okhttp3.RequestBody;
|
||||
import retrofit2.Converter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class JsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
|
||||
@Override
|
||||
public RequestBody convert(T t) throws IOException {
|
||||
return RequestBody.create(MediaType.parse("application/json);charset=UTF-8"), t.toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.yutou.netlibs.converter;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.yutou.netlibs.http.HttpBody;
|
||||
|
||||
import okhttp3.ResponseBody;
|
||||
import retrofit2.Converter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
public class JsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
|
||||
Type type;
|
||||
public JsonResponseBodyConverter(Type type) {
|
||||
this.type=type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T convert(ResponseBody responseBody) throws IOException {
|
||||
String string = new String(responseBody.bytes());
|
||||
responseBody.close();
|
||||
HttpBody<T> body ;
|
||||
try {
|
||||
body = JSONObject.parseObject(string, type);
|
||||
return (T) body;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
body = new HttpBody();
|
||||
body.setSrc(string);
|
||||
}
|
||||
return (T) body;
|
||||
|
||||
}
|
||||
}
|
||||
57
netlibs/src/main/java/com/yutou/netlibs/http/API.java
Normal file
57
netlibs/src/main/java/com/yutou/netlibs/http/API.java
Normal file
@@ -0,0 +1,57 @@
|
||||
package com.yutou.netlibs.http;
|
||||
|
||||
import com.yutou.netlibs.converter.JsonCallAdapter;
|
||||
import com.yutou.netlibs.converter.JsonConverterFactory;
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
|
||||
public class API<T> extends BaseAPI<T> {
|
||||
private String URL;
|
||||
private HashMap<String, String> params;
|
||||
|
||||
public API(String url, HashMap<String, String> params) {
|
||||
this.URL = url;
|
||||
this.params = params;
|
||||
}
|
||||
|
||||
public API(String url) {
|
||||
this.URL = url;
|
||||
this.params = new HashMap<>();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public T createAPI(Class<T> t) {
|
||||
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("http");
|
||||
loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
|
||||
OkHttpClient.Builder builder = new OkHttpClient()
|
||||
.newBuilder()
|
||||
|
||||
.addInterceptor(initQuery())
|
||||
.addInterceptor(loggingInterceptor);
|
||||
return create(builder.build(),
|
||||
JsonConverterFactory.create(),
|
||||
JsonCallAdapter.create(),
|
||||
URL,
|
||||
t);
|
||||
}
|
||||
|
||||
public Interceptor initQuery() {
|
||||
Interceptor addQueryParameterInterceptor = new Interceptor() {
|
||||
@Override
|
||||
public Response intercept(Chain chain) throws IOException {
|
||||
Request request = chain.request();
|
||||
//配置公共参数
|
||||
request = new ParamsContext(params,request).getInRequest();
|
||||
return chain.proceed(request);
|
||||
}
|
||||
};
|
||||
return addQueryParameterInterceptor;
|
||||
}
|
||||
|
||||
}
|
||||
44
netlibs/src/main/java/com/yutou/netlibs/http/BaseAPI.java
Normal file
44
netlibs/src/main/java/com/yutou/netlibs/http/BaseAPI.java
Normal file
@@ -0,0 +1,44 @@
|
||||
package com.yutou.netlibs.http;
|
||||
|
||||
import okhttp3.OkHttpClient;
|
||||
import retrofit2.CallAdapter;
|
||||
import retrofit2.Converter;
|
||||
import retrofit2.Retrofit;
|
||||
|
||||
public abstract class BaseAPI<T> {
|
||||
public abstract T createAPI(Class<T> t);
|
||||
/**
|
||||
* 创建一个接口方法
|
||||
*
|
||||
* @param okHttpClient okhttp客户端
|
||||
* @param converterFactory 处理工厂类
|
||||
* @param callAdapterFactory 请求适配器工厂
|
||||
* @param baseUrl 基础地质
|
||||
* @param service 接口
|
||||
* @return 接口
|
||||
*/
|
||||
public T create(OkHttpClient okHttpClient,
|
||||
Converter.Factory converterFactory,
|
||||
CallAdapter.Factory callAdapterFactory,
|
||||
String baseUrl,
|
||||
Class<T> service) {
|
||||
Retrofit.Builder builder = new Retrofit.Builder()
|
||||
//基础url
|
||||
.baseUrl(baseUrl)
|
||||
//客户端OKHttp
|
||||
.client(okHttpClient);
|
||||
//添加转换工厂
|
||||
if (null != converterFactory) {
|
||||
builder.addConverterFactory(converterFactory);
|
||||
}
|
||||
//添加请求工厂
|
||||
if (null != callAdapterFactory) {
|
||||
builder.addCallAdapterFactory(callAdapterFactory);
|
||||
}
|
||||
//创建retrofit对象
|
||||
Retrofit retrofit = builder.build();
|
||||
|
||||
//返回创建的api
|
||||
return retrofit.create(service);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.yutou.netlibs.http;
|
||||
|
||||
|
||||
import okhttp3.HttpUrl;
|
||||
import okhttp3.Request;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
public class GetRequestParams implements IRequestParam {
|
||||
/**
|
||||
* 构建Request
|
||||
*
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public Request getRequest(HashMap<String, String> map, Request request) {
|
||||
//添加公共参数
|
||||
HttpUrl.Builder builder = request.url().newBuilder();
|
||||
for (String key : map.keySet()) {
|
||||
builder.addQueryParameter(key, String.valueOf(map.get(key)));
|
||||
}
|
||||
return request.newBuilder().url(builder.build()).build();
|
||||
}
|
||||
}
|
||||
40
netlibs/src/main/java/com/yutou/netlibs/http/HttpBody.java
Normal file
40
netlibs/src/main/java/com/yutou/netlibs/http/HttpBody.java
Normal file
@@ -0,0 +1,40 @@
|
||||
package com.yutou.netlibs.http;
|
||||
|
||||
public class HttpBody<T> {
|
||||
private String msg;
|
||||
private int code;
|
||||
private T data;
|
||||
private String src;
|
||||
|
||||
public String getMsg() {
|
||||
return msg;
|
||||
}
|
||||
|
||||
public void setMsg(String msg) {
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public T getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public void setData(T data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public String getSrc() {
|
||||
return src;
|
||||
}
|
||||
|
||||
public void setSrc(String src) {
|
||||
this.src = src;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.yutou.netlibs.http;
|
||||
|
||||
import retrofit2.Call;
|
||||
import retrofit2.Callback;
|
||||
import retrofit2.Response;
|
||||
|
||||
public abstract class HttpCallback<T> implements Callback<HttpBody<T>> {
|
||||
|
||||
public abstract void onResponse(int code,String status,T response);
|
||||
public abstract void onFailure(Throwable throwable);
|
||||
|
||||
@Override
|
||||
public void onResponse(Call<HttpBody<T>> call, Response<HttpBody<T>> response) {
|
||||
if (response.body() != null) {
|
||||
System.out.println("response = " + response.body());
|
||||
System.out.println("response.data = " + response.body().getData());
|
||||
onResponse(response.body().getCode(),response.body().getMsg(),response.body().getData());
|
||||
}else{
|
||||
onFailure(new NullPointerException("response body is null"));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Call<HttpBody<T>> call, Throwable throwable) {
|
||||
onFailure(throwable);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package com.yutou.netlibs.http;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import okhttp3.Connection;
|
||||
import okhttp3.Headers;
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.MediaType;
|
||||
import okhttp3.Protocol;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.RequestBody;
|
||||
import okhttp3.Response;
|
||||
import okhttp3.ResponseBody;
|
||||
import okhttp3.internal.http.HttpHeaders;
|
||||
import okio.Buffer;
|
||||
|
||||
public class HttpLoggingInterceptor implements Interceptor {
|
||||
|
||||
private static final String TAG = "HttpLog";
|
||||
private static final Charset UTF8 = StandardCharsets.UTF_8;
|
||||
|
||||
private volatile Level printLevel = Level.NONE;
|
||||
private java.util.logging.Level colorLevel;
|
||||
private Logger logger;
|
||||
|
||||
public enum Level {
|
||||
NONE, //不打印log
|
||||
BASIC, //只打印 请求首行 和 响应首行
|
||||
HEADERS, //打印请求和响应的所有 Header
|
||||
BODY //所有数据全部打印
|
||||
}
|
||||
|
||||
public HttpLoggingInterceptor(String tag) {
|
||||
logger = Logger.getLogger(tag);
|
||||
colorLevel = java.util.logging.Level.ALL;
|
||||
}
|
||||
|
||||
public void setPrintLevel(Level level) {
|
||||
if (printLevel == null)
|
||||
throw new NullPointerException("printLevel == null. Use Level.NONE instead.");
|
||||
printLevel = level;
|
||||
}
|
||||
|
||||
public void setColorLevel(java.util.logging.Level level) {
|
||||
colorLevel = level;
|
||||
}
|
||||
|
||||
private void log(String message) {
|
||||
logger.log(colorLevel, message);
|
||||
System.err.println(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response intercept(Chain chain) throws IOException {
|
||||
Request request = chain.request();
|
||||
if (printLevel == Level.NONE) {
|
||||
return chain.proceed(request);
|
||||
}
|
||||
|
||||
//请求日志拦截
|
||||
// logForRequest(request, chain.connection());
|
||||
|
||||
//执行请求,计算请求时间
|
||||
long startNs = System.nanoTime();
|
||||
Response response;
|
||||
try {
|
||||
response = chain.proceed(request);
|
||||
} catch (Exception e) {
|
||||
log("<-- HTTP FAILED: " + e);
|
||||
throw e;
|
||||
}
|
||||
long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
|
||||
|
||||
//响应日志拦截
|
||||
return logForResponse(request, response, tookMs);
|
||||
}
|
||||
|
||||
private void logForRequest(Request request, Connection connection) throws IOException {
|
||||
boolean logBody = (printLevel == Level.BODY);
|
||||
boolean logHeaders = (printLevel == Level.BODY || printLevel == Level.HEADERS);
|
||||
RequestBody requestBody = request.body();
|
||||
boolean hasRequestBody = requestBody != null;
|
||||
Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
|
||||
try {
|
||||
String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol;
|
||||
log(requestStartMessage);
|
||||
|
||||
if (logHeaders) {
|
||||
if (hasRequestBody) {
|
||||
// Request body headers are only present when installed as a network interceptor. Force
|
||||
// them to be included (when available) so there values are known.
|
||||
if (requestBody.contentType() != null) {
|
||||
log("\tContent-Type: " + requestBody.contentType());
|
||||
}
|
||||
if (requestBody.contentLength() != -1) {
|
||||
log("\tContent-Length: " + requestBody.contentLength());
|
||||
}
|
||||
}
|
||||
Headers headers = request.headers();
|
||||
for (int i = 0, count = headers.size(); i < count; i++) {
|
||||
String name = headers.name(i);
|
||||
// Skip headers from the request body as they are explicitly logged above.
|
||||
if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
|
||||
log("\t" + name + ": " + headers.value(i));
|
||||
}
|
||||
}
|
||||
|
||||
log(" ");
|
||||
if (logBody && hasRequestBody) {
|
||||
if (isPlaintext(requestBody.contentType())) {
|
||||
bodyToString(request);
|
||||
} else {
|
||||
log("\tbody: maybe [binary body], omitted!");
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.log(colorLevel, "error", e);
|
||||
} finally {
|
||||
log("--> END " + request.method());
|
||||
}
|
||||
}
|
||||
|
||||
private Response logForResponse(Request request, Response response, long tookMs) {
|
||||
Response.Builder builder = response.newBuilder();
|
||||
Response clone = builder.build();
|
||||
ResponseBody responseBody = clone.body();
|
||||
RequestBody requestBody = request.body();
|
||||
boolean hasRequestBody = requestBody != null;
|
||||
boolean logBody = (printLevel == Level.BODY);
|
||||
boolean logHeaders = (printLevel == Level.BODY || printLevel == Level.HEADERS);
|
||||
|
||||
try {
|
||||
log("<-- " + clone.code() + ' ' + clone.message() + ' ' + clone.request().url() + " (" + tookMs + "ms)");
|
||||
if (logHeaders) {
|
||||
Headers headers = clone.headers();
|
||||
for (int i = 0, count = headers.size(); i < count; i++) {
|
||||
log("\t" + headers.name(i) + ": " + headers.value(i));
|
||||
}
|
||||
log(" ");
|
||||
if (logBody && hasRequestBody) {
|
||||
if (isPlaintext(requestBody.contentType())) {
|
||||
bodyToString(request);
|
||||
} else {
|
||||
log("\trequest: maybe [binary body], omitted!");
|
||||
}
|
||||
}
|
||||
if (logBody && HttpHeaders.hasBody(clone)) {
|
||||
if (responseBody == null) return response;
|
||||
|
||||
if (isPlaintext(responseBody.contentType())) {
|
||||
byte[] bytes = responseBody.bytes();// IOUtils.toByteArray(responseBody.byteStream());
|
||||
MediaType contentType = responseBody.contentType();
|
||||
String body = new String(bytes, getCharset(contentType));
|
||||
log("\tbody:" + body);
|
||||
responseBody = ResponseBody.create(responseBody.contentType(), bytes);
|
||||
return response.newBuilder().body(responseBody).build();
|
||||
} else {
|
||||
log("\tbody: maybe [binary body], omitted!");
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.log(colorLevel, "error", e);
|
||||
} finally {
|
||||
log("<-- END HTTP");
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
private static Charset getCharset(MediaType contentType) {
|
||||
Charset charset = contentType != null ? contentType.charset(UTF8) : UTF8;
|
||||
if (charset == null) charset = UTF8;
|
||||
return charset;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the body in question probably contains human readable text. Uses a small sample
|
||||
* of code points to detect unicode control characters commonly used in binary file signatures.
|
||||
*/
|
||||
private static boolean isPlaintext(MediaType mediaType) {
|
||||
if (mediaType == null) return false;
|
||||
if (mediaType.type() != null && mediaType.type().equals("text")) {
|
||||
return true;
|
||||
}
|
||||
String subtype = mediaType.subtype();
|
||||
if (subtype != null) {
|
||||
subtype = subtype.toLowerCase();
|
||||
if (subtype.contains("x-www-form-urlencoded") || subtype.contains("json") || subtype.contains("xml") || subtype.contains("html")) //
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void bodyToString(Request request) {
|
||||
try {
|
||||
Request copy = request.newBuilder().build();
|
||||
RequestBody body = copy.body();
|
||||
if (body == null) return;
|
||||
Buffer buffer = new Buffer();
|
||||
body.writeTo(buffer);
|
||||
Charset charset = getCharset(body.contentType());
|
||||
log("\tbody:" + buffer.readString(charset));
|
||||
} catch (Exception e) {
|
||||
logger.log(colorLevel, "error", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.yutou.netlibs.http;
|
||||
|
||||
import okhttp3.Request;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
public interface IRequestParam {
|
||||
Request getRequest(HashMap<String,String> map, Request request);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.yutou.netlibs.http;
|
||||
|
||||
|
||||
import okhttp3.Request;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
public class ParamsContext {
|
||||
private IRequestParam iRequestParam;
|
||||
private Request request;
|
||||
private HashMap<String,String> map;
|
||||
|
||||
public ParamsContext(HashMap<String,String> map,Request request) {
|
||||
this.map=map;
|
||||
this.request = request;
|
||||
}
|
||||
|
||||
public Request getInRequest() {
|
||||
switch (request.method()) {
|
||||
case "GET":
|
||||
iRequestParam = new GetRequestParams();
|
||||
break;
|
||||
case "POST":
|
||||
iRequestParam = new PostRequestParams();
|
||||
break;
|
||||
}
|
||||
return iRequestParam.getRequest(map,request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.yutou.netlibs.http;
|
||||
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
|
||||
import okhttp3.*;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class PostRequestParams implements IRequestParam {
|
||||
@Override
|
||||
public Request getRequest(HashMap<String, String> map, Request request) {
|
||||
if (request.body() instanceof FormBody) {
|
||||
FormBody.Builder bodyBuilder = new FormBody.Builder();
|
||||
FormBody formBody = (FormBody) request.body();
|
||||
|
||||
for (int i = 0; i < formBody.size(); i++) {
|
||||
bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i));
|
||||
}
|
||||
for (String key : map.keySet()) {
|
||||
bodyBuilder.addEncoded(key, String.valueOf(map.get(key)));
|
||||
}
|
||||
formBody = bodyBuilder.build();
|
||||
request = request.newBuilder().post(formBody).build();
|
||||
} else if (request.body() != null) {
|
||||
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),toUrlParams(map));
|
||||
request = request.newBuilder().post(request.body())
|
||||
.post(requestBody).build();
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
public static String toUrlParams(JSONObject json) {
|
||||
StringBuilder string = new StringBuilder();
|
||||
Set<String> keys = json.keySet();
|
||||
for (String key : keys) {
|
||||
try {
|
||||
string.append("&").append(key).append("=").append(URLEncoder.encode(json.getString(key), "UTF-8"));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
try {
|
||||
string.append("&").append(URLEncoder.encode(key,"UTF-8")).append("=");
|
||||
// string += "&" + key + "=";
|
||||
} catch (Exception e1) {
|
||||
string.append("&").append(key).append("=");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
string = new StringBuilder(string.substring(1, string.length()).replaceAll(" ", ""));
|
||||
return string.toString();
|
||||
}
|
||||
|
||||
public static String toUrlParams(Map<String, String> map) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (String key : map.keySet()) {
|
||||
builder.append(key).append("=").append(map.get(key)).append("&");
|
||||
}
|
||||
return builder.substring(0, builder.length() - 1);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user