liumingming

fix

Showing 65 changed files with 3173 additions and 0 deletions
No preview for this file type
No preview for this file type
*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
... ...
No preview for this file type
OkhttpUtils
\ No newline at end of file
... ...
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<codeStyleSettings language="XML">
<arrangement>
<rules>
<section>
<rule>
<match>
<AND>
<NAME>xmlns:android</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>xmlns:.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*:id</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*:name</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>name</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>style</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
<order>ANDROID_ATTRIBUTE_ORDER</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>.*</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
</rules>
</arrangement>
</codeStyleSettings>
</code_scheme>
</component>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="1.8" />
</component>
</project>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" addBOMForNewFiles="with NO BOM" />
</project>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="testRunner" value="PLATFORM" />
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
</set>
</option>
<option name="resolveModulePerSourceSet" value="false" />
<option name="useQualifiedModuleNames" value="true" />
</GradleProjectSettings>
</option>
</component>
</project>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="BintrayJCenter" />
<option name="name" value="BintrayJCenter" />
<option name="url" value="https://jcenter.bintray.com/" />
</remote-repository>
<remote-repository>
<option name="id" value="Google" />
<option name="name" value="Google" />
<option name="url" value="https://dl.google.com/dl/android/maven2/" />
</remote-repository>
</component>
</project>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CMakeSettings">
<configurations>
<configuration PROFILE_NAME="Debug" CONFIG_NAME="Debug" />
</configurations>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RunConfigurationProducerService">
<option name="ignoredProducers">
<set>
<option value="org.jetbrains.plugins.gradle.execution.test.runner.AllInPackageGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer" />
</set>
</option>
</component>
</project>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
\ No newline at end of file
... ...
No preview for this file type
No preview for this file type
/build
... ...
import java.text.SimpleDateFormat
//apply plugin: 'com.android.application'
apply plugin: 'com.android.library'
static def buildTime() {
def df = new SimpleDateFormat("MMddHHmm")
return df.format(new Date())
}
def baseVersion = "1.0.0"
// versionCode按时间自增
static def increasedVersionCode(){
return (int)(System.currentTimeMillis()/1000/60)
}
android {
compileSdkVersion 28
buildToolsVersion "29.0.2"
defaultConfig {
minSdkVersion 17
targetSdkVersion 28
versionCode increasedVersionCode()
versionName "${baseVersion}.${buildTime()}"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.squareup.okhttp3:okhttp:3.12.1'
}
apply from: 'maven-release-aar.gradle'
\ No newline at end of file
... ...
// 1.maven-插件
apply plugin: 'maven'
// 2.maven-信息
//ext {// ext is a gradle closure allowing the declaration of global properties
// PUBLISH_GROUP_ID = 'com.hhmedic.android.sdk'
// PUBLISH_ARTIFACT_ID = 'nim'
// PUBLISH_VERSION = android.defaultConfig.versionName
//}
def PUBLISH_URL = 'http://develop.hh-medic.com/repository/maven-releases/'
def PUBLISH_GROUP_ID = 'com.hhmedic.android.sdk'
def PUBLISH_ARTIFACT_ID = "okhttputils"
def PUBLISH_VERSION = android.defaultConfig.versionName
// 3.maven-输出路径
uploadArchives {
// repositories.mavenDeployer {
// //这里就是最后输出地址,在自己电脑上新建个文件夹,把文件夹路径粘贴在此
// //注意”file://“ + 路径,有三个斜杠,别漏了
// repository(url: "file:///Workspace/Workshop/HHSDKAndroidOutput")
//
// pom.project {
// groupId project.PUBLISH_GROUP_ID
// artifactId project.PUBLISH_ARTIFACT_ID
// version project.PUBLISH_VERSION
// }
// }
repositories{
mavenDeployer{
repository(url: PUBLISH_URL) {
authentication(userName: "hh-user", password: "hi9rqvdR")
}
pom.groupId = PUBLISH_GROUP_ID
pom.artifactId = PUBLISH_ARTIFACT_ID
pom.version = PUBLISH_VERSION
pom.project {
licenses {
license {
name 'The Apache Software License, Version 2.0'
url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
}
}
}
}
}
}
//以下代码会生成jar包源文件,如果是不开源码,请不要输入这段
//aar包内包含注释
//task androidSourcesJar(type: Jar) {
// classifier = 'sources'
// from android.sourceSets.main.java.sourceFiles
//}
//
//artifacts {
// archives androidSourcesJar
//}
\ No newline at end of file
... ...
# 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
... ...
No preview for this file type
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hhmedic.android.sdk.okhttputils">
</manifest>
\ No newline at end of file
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp;
import com.hhmedic.android.sdk.okhttputils.okhttp.builder.GetBuilder;
import com.hhmedic.android.sdk.okhttputils.okhttp.builder.HeadBuilder;
import com.hhmedic.android.sdk.okhttputils.okhttp.builder.OtherRequestBuilder;
import com.hhmedic.android.sdk.okhttputils.okhttp.builder.PostFileBuilder;
import com.hhmedic.android.sdk.okhttputils.okhttp.builder.PostFormBuilder;
import com.hhmedic.android.sdk.okhttputils.okhttp.builder.PostStringBuilder;
import com.hhmedic.android.sdk.okhttputils.okhttp.callback.Callback;
import com.hhmedic.android.sdk.okhttputils.okhttp.request.RequestCall;
import com.hhmedic.android.sdk.okhttputils.okhttp.utils.Platform;
import java.io.IOException;
import java.util.concurrent.Executor;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Response;
/**
* Created by zhy on 15/8/17.
*/
public class OkHttpUtils
{
public static final long DEFAULT_MILLISECONDS = 10_000L;
private volatile static OkHttpUtils mInstance;
private OkHttpClient mOkHttpClient;
private Platform mPlatform;
public OkHttpUtils(OkHttpClient okHttpClient)
{
if (okHttpClient == null)
{
mOkHttpClient = new OkHttpClient();
} else
{
mOkHttpClient = okHttpClient;
}
mPlatform = Platform.get();
}
public static OkHttpUtils initClient(OkHttpClient okHttpClient)
{
if (mInstance == null)
{
synchronized (OkHttpUtils.class)
{
if (mInstance == null)
{
mInstance = new OkHttpUtils(okHttpClient);
}
}
}
return mInstance;
}
public static OkHttpUtils getInstance()
{
return initClient(null);
}
public Executor getDelivery()
{
return mPlatform.defaultCallbackExecutor();
}
public OkHttpClient getOkHttpClient()
{
return mOkHttpClient;
}
public static GetBuilder get()
{
return new GetBuilder();
}
public static PostStringBuilder postString()
{
return new PostStringBuilder();
}
public static PostFileBuilder postFile()
{
return new PostFileBuilder();
}
public static PostFormBuilder post()
{
return new PostFormBuilder();
}
public static OtherRequestBuilder put()
{
return new OtherRequestBuilder(METHOD.PUT);
}
public static HeadBuilder head()
{
return new HeadBuilder();
}
public static OtherRequestBuilder delete()
{
return new OtherRequestBuilder(METHOD.DELETE);
}
public static OtherRequestBuilder patch()
{
return new OtherRequestBuilder(METHOD.PATCH);
}
public void execute(final RequestCall requestCall, Callback callback)
{
if (callback == null)
callback = Callback.CALLBACK_DEFAULT;
final Callback finalCallback = callback;
final int id = requestCall.getOkHttpRequest().getId();
requestCall.getCall().enqueue(new okhttp3.Callback()
{
@Override
public void onFailure(Call call, final IOException e)
{
sendFailResultCallback(call, e, finalCallback, id);
}
@Override
public void onResponse(final Call call, final Response response)
{
try
{
if (call.isCanceled())
{
sendFailResultCallback(call, new IOException("Canceled!"), finalCallback, id);
return;
}
if (!finalCallback.validateReponse(response, id))
{
sendFailResultCallback(call, new IOException("request failed , reponse's code is : " + response.code()), finalCallback, id);
return;
}
Object o = finalCallback.parseNetworkResponse(response, id);
sendSuccessResultCallback(o, finalCallback, id);
} catch (Exception e)
{
sendFailResultCallback(call, e, finalCallback, id);
} finally
{
if (response.body() != null)
response.body().close();
}
}
});
}
public void sendFailResultCallback(final Call call, final Exception e, final Callback callback, final int id)
{
if (callback == null) return;
mPlatform.execute(new Runnable()
{
@Override
public void run()
{
callback.onError(call, e, id);
callback.onAfter(id);
}
});
}
public void sendSuccessResultCallback(final Object object, final Callback callback, final int id)
{
if (callback == null) return;
mPlatform.execute(new Runnable()
{
@Override
public void run()
{
callback.onResponse(object, id);
callback.onAfter(id);
}
});
}
public void cancelTag(Object tag)
{
for (Call call : mOkHttpClient.dispatcher().queuedCalls())
{
if (tag.equals(call.request().tag()))
{
call.cancel();
}
}
for (Call call : mOkHttpClient.dispatcher().runningCalls())
{
if (tag.equals(call.request().tag()))
{
call.cancel();
}
}
}
public static class METHOD
{
public static final String HEAD = "HEAD";
public static final String DELETE = "DELETE";
public static final String PUT = "PUT";
public static final String PATCH = "PATCH";
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.builder;
import android.net.Uri;
import com.hhmedic.android.sdk.okhttputils.okhttp.request.GetRequest;
import com.hhmedic.android.sdk.okhttputils.okhttp.request.RequestCall;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* Created by zhy on 15/12/14.
*/
public class GetBuilder extends OkHttpRequestBuilder<GetBuilder> implements HasParamsable
{
@Override
public RequestCall build()
{
if (params != null)
{
url = appendParams(url, params);
}
return new GetRequest(url, tag, params, headers,id).build();
}
protected String appendParams(String url, Map<String, String> params)
{
if (url == null || params == null || params.isEmpty())
{
return url;
}
Uri.Builder builder = Uri.parse(url).buildUpon();
Set<String> keys = params.keySet();
Iterator<String> iterator = keys.iterator();
while (iterator.hasNext())
{
String key = iterator.next();
builder.appendQueryParameter(key, params.get(key));
}
return builder.build().toString();
}
@Override
public GetBuilder params(Map<String, String> params)
{
this.params = params;
return this;
}
@Override
public GetBuilder addParams(String key, String val)
{
if (this.params == null)
{
params = new LinkedHashMap<>();
}
params.put(key, val);
return this;
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.builder;
import java.util.Map;
/**
* Created by zhy on 16/3/1.
*/
public interface HasParamsable
{
OkHttpRequestBuilder params(Map<String, String> params);
OkHttpRequestBuilder addParams(String key, String val);
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.builder;
import com.hhmedic.android.sdk.okhttputils.okhttp.OkHttpUtils;
import com.hhmedic.android.sdk.okhttputils.okhttp.request.RequestCall;
import com.hhmedic.android.sdk.okhttputils.okhttp.request.OtherRequest;
/**
* Created by zhy on 16/3/2.
*/
public class HeadBuilder extends GetBuilder
{
@Override
public RequestCall build()
{
return new OtherRequest(null, null, OkHttpUtils.METHOD.HEAD, url, tag, params, headers,id).build();
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.builder;
import com.hhmedic.android.sdk.okhttputils.okhttp.request.RequestCall;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Created by zhy on 15/12/14.
*/
public abstract class OkHttpRequestBuilder<T extends OkHttpRequestBuilder>
{
protected String url;
protected Object tag;
protected Map<String, String> headers;
protected Map<String, String> params;
protected int id;
public T id(int id)
{
this.id = id;
return (T) this;
}
public T url(String url)
{
this.url = url;
return (T) this;
}
public T tag(Object tag)
{
this.tag = tag;
return (T) this;
}
public T headers(Map<String, String> headers)
{
this.headers = headers;
return (T) this;
}
public T addHeader(String key, String val)
{
if (this.headers == null)
{
headers = new LinkedHashMap<>();
}
headers.put(key, val);
return (T) this;
}
public abstract RequestCall build();
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.builder;
import com.hhmedic.android.sdk.okhttputils.okhttp.request.OtherRequest;
import com.hhmedic.android.sdk.okhttputils.okhttp.request.RequestCall;
import okhttp3.RequestBody;
/**
* DELETE、PUT、PATCH等其他方法
*/
public class OtherRequestBuilder extends OkHttpRequestBuilder<OtherRequestBuilder>
{
private RequestBody requestBody;
private String method;
private String content;
public OtherRequestBuilder(String method)
{
this.method = method;
}
@Override
public RequestCall build()
{
return new OtherRequest(requestBody, content, method, url, tag, params, headers,id).build();
}
public OtherRequestBuilder requestBody(RequestBody requestBody)
{
this.requestBody = requestBody;
return this;
}
public OtherRequestBuilder requestBody(String content)
{
this.content = content;
return this;
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.builder;
import com.hhmedic.android.sdk.okhttputils.okhttp.request.PostFileRequest;
import com.hhmedic.android.sdk.okhttputils.okhttp.request.RequestCall;
import java.io.File;
import okhttp3.MediaType;
/**
* Created by zhy on 15/12/14.
*/
public class PostFileBuilder extends OkHttpRequestBuilder<PostFileBuilder>
{
private File file;
private MediaType mediaType;
public OkHttpRequestBuilder file(File file)
{
this.file = file;
return this;
}
public OkHttpRequestBuilder mediaType(MediaType mediaType)
{
this.mediaType = mediaType;
return this;
}
@Override
public RequestCall build()
{
return new PostFileRequest(url, tag, params, headers, file, mediaType,id).build();
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.builder;
import com.hhmedic.android.sdk.okhttputils.okhttp.request.PostFormRequest;
import com.hhmedic.android.sdk.okhttputils.okhttp.request.RequestCall;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Created by zhy on 15/12/14.
*/
public class PostFormBuilder extends OkHttpRequestBuilder<PostFormBuilder> implements HasParamsable
{
private List<FileInput> files = new ArrayList<>();
@Override
public RequestCall build()
{
return new PostFormRequest(url, tag, params, headers, files,id).build();
}
public PostFormBuilder files(String key, Map<String, File> files)
{
for (String filename : files.keySet())
{
this.files.add(new FileInput(key, filename, files.get(filename)));
}
return this;
}
public PostFormBuilder addFile(String name, String filename, File file)
{
files.add(new FileInput(name, filename, file));
return this;
}
public static class FileInput
{
public String key;
public String filename;
public File file;
public FileInput(String name, String filename, File file)
{
this.key = name;
this.filename = filename;
this.file = file;
}
@Override
public String toString()
{
return "FileInput{" +
"key='" + key + '\'' +
", filename='" + filename + '\'' +
", file=" + file +
'}';
}
}
@Override
public PostFormBuilder params(Map<String, String> params)
{
this.params = params;
return this;
}
@Override
public PostFormBuilder addParams(String key, String val)
{
if (this.params == null)
{
params = new LinkedHashMap<>();
}
params.put(key, val);
return this;
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.builder;
import com.hhmedic.android.sdk.okhttputils.okhttp.request.PostStringRequest;
import com.hhmedic.android.sdk.okhttputils.okhttp.request.RequestCall;
import okhttp3.MediaType;
/**
* Created by zhy on 15/12/14.
*/
public class PostStringBuilder extends OkHttpRequestBuilder<PostStringBuilder>
{
private String content;
private MediaType mediaType;
public PostStringBuilder content(String content)
{
this.content = content;
return this;
}
public PostStringBuilder mediaType(MediaType mediaType)
{
this.mediaType = mediaType;
return this;
}
@Override
public RequestCall build()
{
return new PostStringRequest(url, tag, params, headers, content, mediaType,id).build();
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.callback;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import okhttp3.Response;
/**
* Created by zhy on 15/12/14.
*/
public abstract class BitmapCallback extends Callback<Bitmap>
{
@Override
public Bitmap parseNetworkResponse(Response response , int id) throws Exception
{
return BitmapFactory.decodeStream(response.body().byteStream());
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.callback;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;
public abstract class Callback<T>
{
/**
* UI Thread
*
* @param request
*/
public void onBefore(Request request, int id)
{
}
/**
* UI Thread
*
* @param
*/
public void onAfter(int id)
{
}
/**
* UI Thread
*
* @param progress
*/
public void inProgress(float progress, long total , int id)
{
}
/**
* if you parse reponse code in parseNetworkResponse, you should make this method return true.
*
* @param response
* @return
*/
public boolean validateReponse(Response response, int id)
{
return response.isSuccessful();
}
/**
* Thread Pool Thread
*
* @param response
*/
public abstract T parseNetworkResponse(Response response, int id) throws Exception;
public abstract void onError(Call call, Exception e, int id);
public abstract void onResponse(T response, int id);
public static Callback CALLBACK_DEFAULT = new Callback()
{
@Override
public Object parseNetworkResponse(Response response, int id) throws Exception
{
return null;
}
@Override
public void onError(Call call, Exception e, int id)
{
}
@Override
public void onResponse(Object response, int id)
{
}
};
}
\ No newline at end of file
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.callback;
import com.hhmedic.android.sdk.okhttputils.okhttp.OkHttpUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import okhttp3.Response;
/**
* Created by zhy on 15/12/15.
*/
public abstract class FileCallBack extends Callback<File>
{
/**
* 目标文件存储的文件夹路径
*/
private String destFileDir;
/**
* 目标文件存储的文件名
*/
private String destFileName;
public FileCallBack(String destFileDir, String destFileName)
{
this.destFileDir = destFileDir;
this.destFileName = destFileName;
}
@Override
public File parseNetworkResponse(Response response, int id) throws Exception
{
return saveFile(response,id);
}
public File saveFile(Response response,final int id) throws IOException
{
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
try
{
is = response.body().byteStream();
final long total = response.body().contentLength();
long sum = 0;
File dir = new File(destFileDir);
if (!dir.exists())
{
dir.mkdirs();
}
File file = new File(dir, destFileName);
fos = new FileOutputStream(file);
while ((len = is.read(buf)) != -1)
{
sum += len;
fos.write(buf, 0, len);
final long finalSum = sum;
OkHttpUtils.getInstance().getDelivery().execute(new Runnable()
{
@Override
public void run()
{
inProgress(finalSum * 1.0f / total,total,id);
}
});
}
fos.flush();
return file;
} finally
{
try
{
response.body().close();
if (is != null) is.close();
} catch (IOException e)
{
}
try
{
if (fos != null) fos.close();
} catch (IOException e)
{
}
}
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.callback;
import com.hhmedic.android.sdk.okhttputils.okhttp.callback.Callback;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import okhttp3.Response;
/**
* Created by JimGong on 2016/6/23.
*/
public abstract class GenericsCallback<T> extends Callback<T> {
IGenericsSerializator mGenericsSerializator;
public GenericsCallback(IGenericsSerializator serializator) {
mGenericsSerializator = serializator;
}
@Override
public T parseNetworkResponse(Response response, int id) throws IOException {
String string = response.body().string();
Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
if (entityClass == String.class) {
return (T) string;
}
T bean = mGenericsSerializator.transform(string, entityClass);
return bean;
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.callback;
/**
* Created by JimGong on 2016/6/23.
*/
public interface IGenericsSerializator {
<T> T transform(String response, Class<T> classOfT);
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.callback;
import com.hhmedic.android.sdk.okhttputils.okhttp.callback.Callback;
import java.io.IOException;
import okhttp3.Response;
/**
* Created by zhy on 15/12/14.
*/
public abstract class StringCallback extends Callback<String>
{
@Override
public String parseNetworkResponse(Response response, int id) throws IOException
{
return response.body().string();
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.cookie;
import com.hhmedic.android.sdk.okhttputils.okhttp.cookie.store.CookieStore;
import com.hhmedic.android.sdk.okhttputils.okhttp.utils.Exceptions;
import java.util.List;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
/**
* Created by zhy on 16/3/10.
*/
public class CookieJarImpl implements CookieJar
{
private CookieStore cookieStore;
public CookieJarImpl(CookieStore cookieStore)
{
if (cookieStore == null) Exceptions.illegalArgument("cookieStore can not be null.");
this.cookieStore = cookieStore;
}
@Override
public synchronized void saveFromResponse(HttpUrl url, List<Cookie> cookies)
{
cookieStore.add(url, cookies);
}
@Override
public synchronized List<Cookie> loadForRequest(HttpUrl url)
{
return cookieStore.get(url);
}
public CookieStore getCookieStore()
{
return cookieStore;
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.cookie.store;
import java.util.List;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
public interface CookieStore
{
void add(HttpUrl uri, List<Cookie> cookie);
List<Cookie> get(HttpUrl uri);
List<Cookie> getCookies();
boolean remove(HttpUrl uri, Cookie cookie);
boolean removeAll();
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.cookie.store;
/**
* Created by zhy on 16/3/10.
*/
public interface HasCookieStore
{
CookieStore getCookieStore();
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.cookie.store;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
/**
* Created by zhy on 16/3/10.
*/
public class MemoryCookieStore implements CookieStore
{
private final HashMap<String, List<Cookie>> allCookies = new HashMap<>();
@Override
public void add(HttpUrl url, List<Cookie> cookies)
{
List<Cookie> oldCookies = allCookies.get(url.host());
if (oldCookies != null)
{
Iterator<Cookie> itNew = cookies.iterator();
Iterator<Cookie> itOld = oldCookies.iterator();
while (itNew.hasNext())
{
String va = itNew.next().name();
while (va != null && itOld.hasNext())
{
String v = itOld.next().name();
if (v != null && va.equals(v))
{
itOld.remove();
}
}
}
oldCookies.addAll(cookies);
} else
{
allCookies.put(url.host(), cookies);
}
}
@Override
public List<Cookie> get(HttpUrl uri)
{
List<Cookie> cookies = allCookies.get(uri.host());
if (cookies == null)
{
cookies = new ArrayList<>();
allCookies.put(uri.host(), cookies);
}
return cookies;
}
@Override
public boolean removeAll()
{
allCookies.clear();
return true;
}
@Override
public List<Cookie> getCookies()
{
List<Cookie> cookies = new ArrayList<>();
Set<String> httpUrls = allCookies.keySet();
for (String url : httpUrls)
{
cookies.addAll(allCookies.get(url));
}
return cookies;
}
@Override
public boolean remove(HttpUrl uri, Cookie cookie)
{
List<Cookie> cookies = allCookies.get(uri.host());
if (cookie != null)
{
return cookies.remove(cookie);
}
return false;
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.cookie.store;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
/**
* <pre>
* OkHttpClient client = new OkHttpClient.Builder()
* .cookieJar(new JavaNetCookieJar(new CookieManager(
* new PersistentCookieStore(getApplicationContext()),
* CookiePolicy.ACCEPT_ALL))
* .build();
*
* </pre>
* <p/>
* from http://stackoverflow.com/questions/25461792/persistent-cookie-store-using-okhttp-2-on-android
* <p/>
* <br/>
* A persistent cookie store which implements the Apache HttpClient CookieStore interface.
* Cookies are stored and will persist on the user's device between application sessions since they
* are serialized and stored in SharedPreferences. Instances of this class are
* designed to be used with AsyncHttpClient#setCookieStore, but can also be used with a
* regular old apache HttpClient/HttpContext if you prefer.
*/
public class PersistentCookieStore implements CookieStore
{
private static final String LOG_TAG = "PersistentCookieStore";
private static final String COOKIE_PREFS = "CookiePrefsFile";
private static final String COOKIE_NAME_PREFIX = "cookie_";
private final HashMap<String, ConcurrentHashMap<String, Cookie>> cookies;
private final SharedPreferences cookiePrefs;
/**
* Construct a persistent cookie store.
*
* @param context Context to attach cookie store to
*/
public PersistentCookieStore(Context context)
{
cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
cookies = new HashMap<String, ConcurrentHashMap<String, Cookie>>();
// Load any previously stored cookies into the store
Map<String, ?> prefsMap = cookiePrefs.getAll();
for (Map.Entry<String, ?> entry : prefsMap.entrySet())
{
if (((String) entry.getValue()) != null && !((String) entry.getValue()).startsWith(COOKIE_NAME_PREFIX))
{
String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
for (String name : cookieNames)
{
String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
if (encodedCookie != null)
{
Cookie decodedCookie = decodeCookie(encodedCookie);
if (decodedCookie != null)
{
if (!cookies.containsKey(entry.getKey()))
cookies.put(entry.getKey(), new ConcurrentHashMap<String, Cookie>());
cookies.get(entry.getKey()).put(name, decodedCookie);
}
}
}
}
}
}
protected void add(HttpUrl uri, Cookie cookie)
{
String name = getCookieToken(cookie);
if (cookie.persistent())
{
if (!cookies.containsKey(uri.host()))
{
cookies.put(uri.host(), new ConcurrentHashMap<String, Cookie>());
}
cookies.get(uri.host()).put(name, cookie);
} else
{
if (cookies.containsKey(uri.host()))
{
cookies.get(uri.host()).remove(name);
}else
{
return ;
}
}
// Save cookie into persistent store
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.putString(uri.host(), TextUtils.join(",", cookies.get(uri.host()).keySet()));
prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableHttpCookie(cookie)));
prefsWriter.apply();
}
protected String getCookieToken(Cookie cookie)
{
return cookie.name() + cookie.domain();
}
@Override
public void add(HttpUrl uri, List<Cookie> cookies)
{
for (Cookie cookie : cookies)
{
add(uri, cookie);
}
}
@Override
public List<Cookie> get(HttpUrl uri)
{
ArrayList<Cookie> ret = new ArrayList<Cookie>();
if (cookies.containsKey(uri.host()))
{
Collection<Cookie> cookies = this.cookies.get(uri.host()).values();
for (Cookie cookie : cookies)
{
if (isCookieExpired(cookie))
{
remove(uri, cookie);
} else
{
ret.add(cookie);
}
}
}
return ret;
}
private static boolean isCookieExpired(Cookie cookie)
{
return cookie.expiresAt() < System.currentTimeMillis();
}
@Override
public boolean removeAll()
{
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.clear();
prefsWriter.apply();
cookies.clear();
return true;
}
@Override
public boolean remove(HttpUrl uri, Cookie cookie)
{
String name = getCookieToken(cookie);
if (cookies.containsKey(uri.host()) && cookies.get(uri.host()).containsKey(name))
{
cookies.get(uri.host()).remove(name);
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
if (cookiePrefs.contains(COOKIE_NAME_PREFIX + name))
{
prefsWriter.remove(COOKIE_NAME_PREFIX + name);
}
prefsWriter.putString(uri.host(), TextUtils.join(",", cookies.get(uri.host()).keySet()));
prefsWriter.apply();
return true;
} else
{
return false;
}
}
@Override
public List<Cookie> getCookies()
{
ArrayList<Cookie> ret = new ArrayList<Cookie>();
for (String key : cookies.keySet())
ret.addAll(cookies.get(key).values());
return ret;
}
protected String encodeCookie(SerializableHttpCookie cookie)
{
if (cookie == null)
return null;
ByteArrayOutputStream os = new ByteArrayOutputStream();
try
{
ObjectOutputStream outputStream = new ObjectOutputStream(os);
outputStream.writeObject(cookie);
} catch (IOException e)
{
Log.d(LOG_TAG, "IOException in encodeCookie", e);
return null;
}
return byteArrayToHexString(os.toByteArray());
}
protected Cookie decodeCookie(String cookieString)
{
byte[] bytes = hexStringToByteArray(cookieString);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
Cookie cookie = null;
try
{
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
cookie = ((SerializableHttpCookie) objectInputStream.readObject()).getCookie();
} catch (IOException e)
{
Log.d(LOG_TAG, "IOException in decodeCookie", e);
} catch (ClassNotFoundException e)
{
Log.d(LOG_TAG, "ClassNotFoundException in decodeCookie", e);
}
return cookie;
}
/**
* Using some super basic byte array &lt;-&gt; hex conversions so we don't have to rely on any
* large Base64 libraries. Can be overridden if you like!
*
* @param bytes byte array to be converted
* @return string containing hex values
*/
protected String byteArrayToHexString(byte[] bytes)
{
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte element : bytes)
{
int v = element & 0xff;
if (v < 16)
{
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase(Locale.US);
}
/**
* Converts hex values from strings to byte arra
*
* @param hexString string of hex-encoded values
* @return decoded byte array
*/
protected byte[] hexStringToByteArray(String hexString)
{
int len = hexString.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2)
{
data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
}
return data;
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.cookie.store;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import okhttp3.Cookie;
/**
* from http://stackoverflow.com/questions/25461792/persistent-cookie-store-using-okhttp-2-on-android
* and<br/>
* http://www.geebr.com/post/okHttp3%E4%B9%8BCookies%E7%AE%A1%E7%90%86%E5%8F%8A%E6%8C%81%E4%B9%85%E5%8C%96
*/
public class SerializableHttpCookie implements Serializable
{
private static final long serialVersionUID = 6374381323722046732L;
private transient final Cookie cookie;
private transient Cookie clientCookie;
public SerializableHttpCookie(Cookie cookie)
{
this.cookie = cookie;
}
public Cookie getCookie()
{
Cookie bestCookie = cookie;
if (clientCookie != null)
{
bestCookie = clientCookie;
}
return bestCookie;
}
private void writeObject(ObjectOutputStream out) throws IOException
{
out.writeObject(cookie.name());
out.writeObject(cookie.value());
out.writeLong(cookie.expiresAt());
out.writeObject(cookie.domain());
out.writeObject(cookie.path());
out.writeBoolean(cookie.secure());
out.writeBoolean(cookie.httpOnly());
out.writeBoolean(cookie.hostOnly());
out.writeBoolean(cookie.persistent());
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
{
String name = (String) in.readObject();
String value = (String) in.readObject();
long expiresAt = in.readLong();
String domain = (String) in.readObject();
String path = (String) in.readObject();
boolean secure = in.readBoolean();
boolean httpOnly = in.readBoolean();
boolean hostOnly = in.readBoolean();
boolean persistent = in.readBoolean();
Cookie.Builder builder = new Cookie.Builder();
builder = builder.name(name);
builder = builder.value(value);
builder = builder.expiresAt(expiresAt);
builder = hostOnly ? builder.hostOnlyDomain(domain) : builder.domain(domain);
builder = builder.path(path);
builder = secure ? builder.secure() : builder;
builder = httpOnly ? builder.httpOnly() : builder;
clientCookie = builder.build();
}
}
\ No newline at end of file
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.log;
import android.text.TextUtils;
import android.util.Log;
import java.io.IOException;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
/**
* Created by zhy on 16/3/1.
*/
public class LoggerInterceptor implements Interceptor
{
public static final String TAG = "OkHttpUtils";
private String tag;
private boolean showResponse;
public LoggerInterceptor(String tag, boolean showResponse)
{
if (TextUtils.isEmpty(tag))
{
tag = TAG;
}
this.showResponse = showResponse;
this.tag = tag;
}
public LoggerInterceptor(String tag)
{
this(tag, false);
}
@Override
public Response intercept(Chain chain) throws IOException
{
Request request = chain.request();
logForRequest(request);
Response response = chain.proceed(request);
return logForResponse(response);
}
private Response logForResponse(Response response)
{
try
{
//===>response log
Log.e(tag, "========response'log=======");
Response.Builder builder = response.newBuilder();
Response clone = builder.build();
Log.e(tag, "url : " + clone.request().url());
Log.e(tag, "code : " + clone.code());
Log.e(tag, "protocol : " + clone.protocol());
if (!TextUtils.isEmpty(clone.message()))
Log.e(tag, "message : " + clone.message());
if (showResponse)
{
ResponseBody body = clone.body();
if (body != null)
{
MediaType mediaType = body.contentType();
if (mediaType != null)
{
Log.e(tag, "responseBody's contentType : " + mediaType.toString());
if (isText(mediaType))
{
String resp = body.string();
Log.e(tag, "responseBody's content : " + resp);
body = ResponseBody.create(mediaType, resp);
return response.newBuilder().body(body).build();
} else
{
Log.e(tag, "responseBody's content : " + " maybe [file part] , too large too print , ignored!");
}
}
}
}
Log.e(tag, "========response'log=======end");
} catch (Exception e)
{
// e.printStackTrace();
}
return response;
}
private void logForRequest(Request request)
{
try
{
String url = request.url().toString();
Headers headers = request.headers();
Log.e(tag, "========request'log=======");
Log.e(tag, "method : " + request.method());
Log.e(tag, "url : " + url);
if (headers != null && headers.size() > 0)
{
Log.e(tag, "headers : " + headers.toString());
}
RequestBody requestBody = request.body();
if (requestBody != null)
{
MediaType mediaType = requestBody.contentType();
if (mediaType != null)
{
Log.e(tag, "requestBody's contentType : " + mediaType.toString());
if (isText(mediaType))
{
Log.e(tag, "requestBody's content : " + bodyToString(request));
} else
{
Log.e(tag, "requestBody's content : " + " maybe [file part] , too large too print , ignored!");
}
}
}
Log.e(tag, "========request'log=======end");
} catch (Exception e)
{
// e.printStackTrace();
}
}
private boolean isText(MediaType mediaType)
{
if (mediaType.type() != null && mediaType.type().equals("text"))
{
return true;
}
if (mediaType.subtype() != null)
{
if (mediaType.subtype().equals("json") ||
mediaType.subtype().equals("xml") ||
mediaType.subtype().equals("html") ||
mediaType.subtype().equals("webviewhtml")
)
return true;
}
return false;
}
private String bodyToString(final Request request)
{
try
{
final Request copy = request.newBuilder().build();
final Buffer buffer = new Buffer();
copy.body().writeTo(buffer);
return buffer.readUtf8();
} catch (final IOException e)
{
return "something error when show requestBody.";
}
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.request;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import java.io.IOException;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;
/**
* Decorates an OkHttp request body to count the number of bytes written when writing it. Can
* decorate any request body, but is most useful for tracking the upload progress of large
* multipart requests.
*
* @author Leo Nikkilä
*/
public class CountingRequestBody extends RequestBody
{
protected RequestBody delegate;
protected Listener listener;
protected CountingSink countingSink;
public CountingRequestBody(RequestBody delegate, Listener listener)
{
this.delegate = delegate;
this.listener = listener;
}
@Override
public MediaType contentType()
{
return delegate.contentType();
}
@Override
public long contentLength()
{
try
{
return delegate.contentLength();
} catch (IOException e)
{
e.printStackTrace();
}
return -1;
}
@Override
public void writeTo(BufferedSink sink) throws IOException
{
countingSink = new CountingSink(sink);
BufferedSink bufferedSink = Okio.buffer(countingSink);
delegate.writeTo(bufferedSink);
bufferedSink.flush();
}
protected final class CountingSink extends ForwardingSink
{
private long bytesWritten = 0;
public CountingSink(Sink delegate)
{
super(delegate);
}
@Override
public void write(Buffer source, long byteCount) throws IOException
{
super.write(source, byteCount);
bytesWritten += byteCount;
listener.onRequestProgress(bytesWritten, contentLength());
}
}
public static interface Listener
{
public void onRequestProgress(long bytesWritten, long contentLength);
}
}
\ No newline at end of file
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.request;
import java.util.Map;
import okhttp3.Request;
import okhttp3.RequestBody;
/**
* Created by zhy on 15/12/14.
*/
public class GetRequest extends OkHttpRequest
{
public GetRequest(String url, Object tag, Map<String, String> params, Map<String, String> headers,int id)
{
super(url, tag, params, headers,id);
}
@Override
protected RequestBody buildRequestBody()
{
return null;
}
@Override
protected Request buildRequest(RequestBody requestBody)
{
return builder.get().build();
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.request;
import com.hhmedic.android.sdk.okhttputils.okhttp.callback.Callback;
import com.hhmedic.android.sdk.okhttputils.okhttp.utils.Exceptions;
import java.util.Map;
import okhttp3.Headers;
import okhttp3.Request;
import okhttp3.RequestBody;
/**
* Created by zhy on 15/11/6.
*/
public abstract class OkHttpRequest
{
protected String url;
protected Object tag;
protected Map<String, String> params;
protected Map<String, String> headers;
protected int id;
protected Request.Builder builder = new Request.Builder();
protected OkHttpRequest(String url, Object tag,
Map<String, String> params, Map<String, String> headers,int id)
{
this.url = url;
this.tag = tag;
this.params = params;
this.headers = headers;
this.id = id ;
if (url == null)
{
Exceptions.illegalArgument("url can not be null.");
}
initBuilder();
}
/**
* 初始化一些基本参数 url , tag , headers
*/
private void initBuilder()
{
builder.url(url).tag(tag);
appendHeaders();
}
protected abstract RequestBody buildRequestBody();
protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback)
{
return requestBody;
}
protected abstract Request buildRequest(RequestBody requestBody);
public RequestCall build()
{
return new RequestCall(this);
}
public Request generateRequest(Callback callback)
{
RequestBody requestBody = buildRequestBody();
RequestBody wrappedRequestBody = wrapRequestBody(requestBody, callback);
Request request = buildRequest(wrappedRequestBody);
return request;
}
protected void appendHeaders()
{
Headers.Builder headerBuilder = new Headers.Builder();
if (headers == null || headers.isEmpty()) return;
for (String key : headers.keySet())
{
headerBuilder.add(key, headers.get(key));
}
builder.headers(headerBuilder.build());
}
public int getId()
{
return id ;
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.request;
import android.text.TextUtils;
import com.hhmedic.android.sdk.okhttputils.okhttp.OkHttpUtils;
import com.hhmedic.android.sdk.okhttputils.okhttp.utils.Exceptions;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.internal.http.HttpMethod;
/**
* Created by zhy on 16/2/23.
*/
public class OtherRequest extends OkHttpRequest
{
private static MediaType MEDIA_TYPE_PLAIN = MediaType.parse("text/plain;charset=utf-8");
private RequestBody requestBody;
private String method;
private String content;
public OtherRequest(RequestBody requestBody, String content, String method, String url, Object tag, Map<String, String> params, Map<String, String> headers,int id)
{
super(url, tag, params, headers,id);
this.requestBody = requestBody;
this.method = method;
this.content = content;
}
@Override
protected RequestBody buildRequestBody()
{
if (requestBody == null && TextUtils.isEmpty(content) && HttpMethod.requiresRequestBody(method))
{
Exceptions.illegalArgument("requestBody and content can not be null in method:" + method);
}
if (requestBody == null && !TextUtils.isEmpty(content))
{
requestBody = RequestBody.create(MEDIA_TYPE_PLAIN, content);
}
return requestBody;
}
@Override
protected Request buildRequest(RequestBody requestBody)
{
if (method.equals(OkHttpUtils.METHOD.PUT))
{
builder.put(requestBody);
} else if (method.equals(OkHttpUtils.METHOD.DELETE))
{
if (requestBody == null)
builder.delete();
else
builder.delete(requestBody);
} else if (method.equals(OkHttpUtils.METHOD.HEAD))
{
builder.head();
} else if (method.equals(OkHttpUtils.METHOD.PATCH))
{
builder.patch(requestBody);
}
return builder.build();
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.request;
import com.hhmedic.android.sdk.okhttputils.okhttp.OkHttpUtils;
import com.hhmedic.android.sdk.okhttputils.okhttp.callback.Callback;
import com.hhmedic.android.sdk.okhttputils.okhttp.utils.Exceptions;
import java.io.File;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
/**
* Created by zhy on 15/12/14.
*/
public class PostFileRequest extends OkHttpRequest
{
private static MediaType MEDIA_TYPE_STREAM = MediaType.parse("application/octet-stream");
private File file;
private MediaType mediaType;
public PostFileRequest(String url, Object tag, Map<String, String> params, Map<String, String> headers, File file, MediaType mediaType,int id)
{
super(url, tag, params, headers,id);
this.file = file;
this.mediaType = mediaType;
if (this.file == null)
{
Exceptions.illegalArgument("the file can not be null !");
}
if (this.mediaType == null)
{
this.mediaType = MEDIA_TYPE_STREAM;
}
}
@Override
protected RequestBody buildRequestBody()
{
return RequestBody.create(mediaType, file);
}
@Override
protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback)
{
if (callback == null) return requestBody;
CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody, new CountingRequestBody.Listener()
{
@Override
public void onRequestProgress(final long bytesWritten, final long contentLength)
{
OkHttpUtils.getInstance().getDelivery().execute(new Runnable()
{
@Override
public void run()
{
callback.inProgress(bytesWritten * 1.0f / contentLength,contentLength,id);
}
});
}
});
return countingRequestBody;
}
@Override
protected Request buildRequest(RequestBody requestBody)
{
return builder.post(requestBody).build();
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.request;
import com.hhmedic.android.sdk.okhttputils.okhttp.OkHttpUtils;
import com.hhmedic.android.sdk.okhttputils.okhttp.builder.PostFormBuilder;
import com.hhmedic.android.sdk.okhttputils.okhttp.callback.Callback;
import java.io.UnsupportedEncodingException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
/**
* Created by zhy on 15/12/14.
*/
public class PostFormRequest extends OkHttpRequest
{
private List<PostFormBuilder.FileInput> files;
public PostFormRequest(String url, Object tag, Map<String, String> params, Map<String, String> headers, List<PostFormBuilder.FileInput> files,int id)
{
super(url, tag, params, headers,id);
this.files = files;
}
@Override
protected RequestBody buildRequestBody()
{
if (files == null || files.isEmpty())
{
FormBody.Builder builder = new FormBody.Builder();
addParams(builder);
FormBody formBody = builder.build();
return formBody;
} else
{
MultipartBody.Builder builder = new MultipartBody.Builder()
.setType(MultipartBody.FORM);
addParams(builder);
for (int i = 0; i < files.size(); i++)
{
PostFormBuilder.FileInput fileInput = files.get(i);
RequestBody fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileInput.filename)), fileInput.file);
builder.addFormDataPart(fileInput.key, fileInput.filename, fileBody);
}
return builder.build();
}
}
@Override
protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback)
{
if (callback == null) return requestBody;
CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody, new CountingRequestBody.Listener()
{
@Override
public void onRequestProgress(final long bytesWritten, final long contentLength)
{
OkHttpUtils.getInstance().getDelivery().execute(new Runnable()
{
@Override
public void run()
{
callback.inProgress(bytesWritten * 1.0f / contentLength,contentLength,id);
}
});
}
});
return countingRequestBody;
}
@Override
protected Request buildRequest(RequestBody requestBody)
{
return builder.post(requestBody).build();
}
private String guessMimeType(String path)
{
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String contentTypeFor = null;
try
{
contentTypeFor = fileNameMap.getContentTypeFor(URLEncoder.encode(path, "UTF-8"));
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
if (contentTypeFor == null)
{
contentTypeFor = "application/octet-stream";
}
return contentTypeFor;
}
private void addParams(MultipartBody.Builder builder)
{
if (params != null && !params.isEmpty())
{
for (String key : params.keySet())
{
builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
RequestBody.create(null, params.get(key)));
}
}
}
private void addParams(FormBody.Builder builder)
{
if (params != null)
{
for (String key : params.keySet())
{
builder.add(key, params.get(key));
}
}
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.request;
import com.hhmedic.android.sdk.okhttputils.okhttp.utils.Exceptions;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
/**
* Created by zhy on 15/12/14.
*/
public class PostStringRequest extends OkHttpRequest
{
private static MediaType MEDIA_TYPE_PLAIN = MediaType.parse("text/plain;charset=utf-8");
private String content;
private MediaType mediaType;
public PostStringRequest(String url, Object tag, Map<String, String> params, Map<String, String> headers, String content, MediaType mediaType,int id)
{
super(url, tag, params, headers,id);
this.content = content;
this.mediaType = mediaType;
if (this.content == null)
{
Exceptions.illegalArgument("the content can not be null !");
}
if (this.mediaType == null)
{
this.mediaType = MEDIA_TYPE_PLAIN;
}
}
@Override
protected RequestBody buildRequestBody()
{
return RequestBody.create(mediaType, content);
}
@Override
protected Request buildRequest( RequestBody requestBody)
{
return builder.post(requestBody).build();
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.request;
import com.hhmedic.android.sdk.okhttputils.okhttp.OkHttpUtils;
import com.hhmedic.android.sdk.okhttputils.okhttp.callback.Callback;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by zhy on 15/12/15.
* 对OkHttpRequest的封装,对外提供更多的接口:cancel(),readTimeOut()...
*/
public class RequestCall
{
private OkHttpRequest okHttpRequest;
private Request request;
private Call call;
private long readTimeOut;
private long writeTimeOut;
private long connTimeOut;
private OkHttpClient clone;
public RequestCall(OkHttpRequest request)
{
this.okHttpRequest = request;
}
public RequestCall readTimeOut(long readTimeOut)
{
this.readTimeOut = readTimeOut;
return this;
}
public RequestCall writeTimeOut(long writeTimeOut)
{
this.writeTimeOut = writeTimeOut;
return this;
}
public RequestCall connTimeOut(long connTimeOut)
{
this.connTimeOut = connTimeOut;
return this;
}
public Call buildCall(Callback callback)
{
request = generateRequest(callback);
if (readTimeOut > 0 || writeTimeOut > 0 || connTimeOut > 0)
{
readTimeOut = readTimeOut > 0 ? readTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS;
writeTimeOut = writeTimeOut > 0 ? writeTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS;
connTimeOut = connTimeOut > 0 ? connTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS;
clone = OkHttpUtils.getInstance().getOkHttpClient().newBuilder()
.readTimeout(readTimeOut, TimeUnit.MILLISECONDS)
.writeTimeout(writeTimeOut, TimeUnit.MILLISECONDS)
.connectTimeout(connTimeOut, TimeUnit.MILLISECONDS)
.build();
call = clone.newCall(request);
} else
{
call = OkHttpUtils.getInstance().getOkHttpClient().newCall(request);
}
return call;
}
private Request generateRequest(Callback callback)
{
return okHttpRequest.generateRequest(callback);
}
public void execute(Callback callback)
{
buildCall(callback);
if (callback != null)
{
callback.onBefore(request, getOkHttpRequest().getId());
}
OkHttpUtils.getInstance().execute(this, callback);
}
public Call getCall()
{
return call;
}
public Request getRequest()
{
return request;
}
public OkHttpRequest getOkHttpRequest()
{
return okHttpRequest;
}
public Response execute() throws IOException
{
buildCall(null);
return call.execute();
}
public void cancel()
{
if (call != null)
{
call.cancel();
}
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.utils;
/**
* Created by zhy on 15/12/14.
*/
public class Exceptions
{
public static void illegalArgument(String msg, Object... params)
{
throw new IllegalArgumentException(String.format(msg, params));
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.utils;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.io.InputStream;
import java.lang.reflect.Field;
/**
* Created by zhy on 15/11/6.
*/
public class ImageUtils
{
/**
* 根据InputStream获取图片实际的宽度和高度
*
* @param imageStream
* @return
*/
public static ImageSize getImageSize(InputStream imageStream)
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(imageStream, null, options);
return new ImageSize(options.outWidth, options.outHeight);
}
public static class ImageSize
{
int width;
int height;
public ImageSize()
{
}
public ImageSize(int width, int height)
{
this.width = width;
this.height = height;
}
@Override
public String toString()
{
return "ImageSize{" +
"width=" + width +
", height=" + height +
'}';
}
}
public static int calculateInSampleSize(ImageSize srcSize, ImageSize targetSize)
{
// 源图片的宽度
int width = srcSize.width;
int height = srcSize.height;
int inSampleSize = 1;
int reqWidth = targetSize.width;
int reqHeight = targetSize.height;
if (width > reqWidth && height > reqHeight)
{
// 计算出实际宽度和目标宽度的比率
int widthRatio = Math.round((float) width / (float) reqWidth);
int heightRatio = Math.round((float) height / (float) reqHeight);
inSampleSize = Math.max(widthRatio, heightRatio);
}
return inSampleSize;
}
/**
* 根据ImageView获适当的压缩的宽和高
*
* @param view
* @return
*/
public static ImageSize getImageViewSize(View view)
{
ImageSize imageSize = new ImageSize();
imageSize.width = getExpectWidth(view);
imageSize.height = getExpectHeight(view);
return imageSize;
}
/**
* 根据view获得期望的高度
*
* @param view
* @return
*/
private static int getExpectHeight(View view)
{
int height = 0;
if (view == null) return 0;
final ViewGroup.LayoutParams params = view.getLayoutParams();
//如果是WRAP_CONTENT,此时图片还没加载,getWidth根本无效
if (params != null && params.height != ViewGroup.LayoutParams.WRAP_CONTENT)
{
height = view.getWidth(); // 获得实际的宽度
}
if (height <= 0 && params != null)
{
height = params.height; // 获得布局文件中的声明的宽度
}
if (height <= 0)
{
height = getImageViewFieldValue(view, "mMaxHeight");// 获得设置的最大的宽度
}
//如果宽度还是没有获取到,憋大招,使用屏幕的宽度
if (height <= 0)
{
DisplayMetrics displayMetrics = view.getContext().getResources()
.getDisplayMetrics();
height = displayMetrics.heightPixels;
}
return height;
}
/**
* 根据view获得期望的宽度
*
* @param view
* @return
*/
private static int getExpectWidth(View view)
{
int width = 0;
if (view == null) return 0;
final ViewGroup.LayoutParams params = view.getLayoutParams();
//如果是WRAP_CONTENT,此时图片还没加载,getWidth根本无效
if (params != null && params.width != ViewGroup.LayoutParams.WRAP_CONTENT)
{
width = view.getWidth(); // 获得实际的宽度
}
if (width <= 0 && params != null)
{
width = params.width; // 获得布局文件中的声明的宽度
}
if (width <= 0)
{
width = getImageViewFieldValue(view, "mMaxWidth");// 获得设置的最大的宽度
}
//如果宽度还是没有获取到,憋大招,使用屏幕的宽度
if (width <= 0)
{
DisplayMetrics displayMetrics = view.getContext().getResources()
.getDisplayMetrics();
width = displayMetrics.widthPixels;
}
return width;
}
/**
* 通过反射获取imageview的某个属性值
*
* @param object
* @param fieldName
* @return
*/
private static int getImageViewFieldValue(Object object, String fieldName)
{
int value = 0;
try
{
Field field = ImageView.class.getDeclaredField(fieldName);
field.setAccessible(true);
int fieldValue = field.getInt(object);
if (fieldValue > 0 && fieldValue < Integer.MAX_VALUE)
{
value = fieldValue;
}
} catch (Exception e)
{
}
return value;
}
}
... ...
package com.hhmedic.android.sdk.okhttputils.okhttp.utils;
import android.util.Log;
/**
* Created by zhy on 15/11/6.
*/
public class L
{
private static boolean debug = false;
public static void e(String msg)
{
if (debug)
{
Log.e("OkHttp", msg);
}
}
}
... ...
/*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hhmedic.android.sdk.okhttputils.okhttp.utils;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class Platform
{
private static final Platform PLATFORM = findPlatform();
public static Platform get()
{
L.e(PLATFORM.getClass().toString());
return PLATFORM;
}
private static Platform findPlatform()
{
try
{
Class.forName("android.os.Build");
if (Build.VERSION.SDK_INT != 0)
{
return new Android();
}
} catch (ClassNotFoundException ignored)
{
}
return new Platform();
}
public Executor defaultCallbackExecutor()
{
return Executors.newCachedThreadPool();
}
public void execute(Runnable runnable)
{
defaultCallbackExecutor().execute(runnable);
}
static class Android extends Platform
{
@Override
public Executor defaultCallbackExecutor()
{
return new MainThreadExecutor();
}
static class MainThreadExecutor implements Executor
{
private final Handler handler = new Handler(Looper.getMainLooper());
@Override
public void execute(Runnable r)
{
handler.post(r);
}
}
}
}
... ...
No preview for this file type
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
... ...
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
... ...
No preview for this file type
#Thu Jul 23 17:56:04 CST 2020
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip
... ...
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
... ...
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
... ...
rootProject.name='OkhttpUtils'
include ':app'
... ...