提交 a799db29 编写于 作者: B Blankj

see 02/25 log

上级 c66a1449
......@@ -18,7 +18,7 @@ public final class RegexConstants {
* Regex of exact mobile.
* <p>china mobile: 134(0-8), 135, 136, 137, 138, 139, 147, 150, 151, 152, 157, 158, 159, 178, 182, 183, 184, 187, 188, 198</p>
* <p>china unicom: 130, 131, 132, 145, 155, 156, 166, 171, 175, 176, 185, 186</p>
* <p>china telecom: 133, 153, 173, 177, 180, 181, 189, 199</p>
* <p>china telecom: 133, 153, 173, 177, 180, 181, 189, 199, 191</p>
* <p>global star: 1349</p>
* <p>virtual operator: 170</p>
*/
......
......@@ -787,6 +787,7 @@ public final class AppUtils {
PackageInfo pi = pm.getPackageArchiveInfo(apkFilePath, 0);
ApplicationInfo appInfo = pi.applicationInfo;
appInfo.sourceDir = apkFilePath;
appInfo.publicSourceDir = apkFilePath;
return getBean(pm, pi);
}
......
......@@ -185,9 +185,9 @@ public final class SnackbarUtils {
/**
* Show the snackbar.
*/
public void show() {
public Snackbar show() {
final View view = this.view;
if (view == null) return;
if (view == null) return null;
if (messageColor != COLOR_DEFAULT) {
SpannableString spannableString = new SpannableString(message);
ForegroundColorSpan colorSpan = new ForegroundColorSpan(messageColor);
......@@ -217,6 +217,7 @@ public final class SnackbarUtils {
snackbar.setAction(actionText, actionListener);
}
snackbar.show();
return snackbar;
}
/**
......
package com.blankj.utilcode.util.http;
public interface Chain {
}
package com.blankj.utilcode.util.http;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public final class ExecutorFactory {
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final Executor DEFAULT_WORK_EXECUTOR = new ThreadPoolExecutor(2 * CPU_COUNT + 1,
2 * CPU_COUNT + 1,
30, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(128),
new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(@NonNull Runnable r) {
return new Thread(r, "http-pool-" + mCount.getAndIncrement());
}
}
);
private static final Executor DEFAULT_MAIN_EXECUTOR = new Executor() {
private final Handler mHandler = new Handler(Looper.getMainLooper());
@Override
public void execute(@NonNull Runnable command) {
mHandler.post(command);
}
};
public static Executor getDefaultWorkExecutor() {
return DEFAULT_WORK_EXECUTOR;
}
public static Executor getDefaultMainExecutor() {
return DEFAULT_MAIN_EXECUTOR;
}
}
package com.blankj.utilcode.util.http;
import android.accounts.NetworkErrorException;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.security.cert.X509Certificate;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2019/02/08
* desc : utils about http
* </pre>
*/
public final class HttpUtils {
private static final String BOUNDARY = java.util.UUID.randomUUID().toString();
private static final String TWO_HYPHENS = "--";
private static final int CONNECT_TIMEOUT_TIME = 15000;
private static final int READ_TIMEOUT_TIME = 19000;
private static final int BUFFER_SIZE = 8192;
private static final TrustManager[] DEFAULT_TRUST_MANAGERS = new TrustManager[]{
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@SuppressLint("TrustAllX509TrustManager")
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) { /**/ }
@SuppressLint("TrustAllX509TrustManager")
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) { /**/ }
}
};
private static final HostnameVerifier DEFAULT_VERIFIER = new HostnameVerifier() {
@SuppressLint("BadHostnameVerifier")
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
private static final Config CONFIG = new Config();
private final Config mConfig;
private static HttpUtils sHttpUtils;
private HttpUtils(@NonNull Config config) {
mConfig = config;
}
public static HttpUtils getInstance(@NonNull Config config) {
if (sHttpUtils == null) {
synchronized (HttpUtils.class) {
sHttpUtils = new HttpUtils(config);
}
}
return sHttpUtils;
}
public static void call(@NonNull final Request request, @NonNull final ResponseCallback callback) {
new Call(request, callback).run();
}
private static HttpURLConnection getConnection(final Request request) throws IOException {
HttpURLConnection conn = (HttpURLConnection) request.mURL.openConnection();
if (conn instanceof HttpsURLConnection) {
HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
trustAllHosts(httpsConn);
}
addHeader(conn, request.mHeader);
addBody(conn, request.mBody);
conn.setConnectTimeout(CONFIG.connectTimeout);
conn.setReadTimeout(CONFIG.readTimeout);
conn.setUseCaches(CONFIG.useCaches);
return conn;
}
private static void addBody(HttpURLConnection conn, Request.Body body) throws IOException {
if (body == null) {
conn.setRequestMethod("GET");
} else {
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setRequestProperty("content-type", body.mediaType);
if (body.length > 0) {
conn.setRequestProperty("content-length", String.valueOf(body.length));
}
BufferedOutputStream bos = new BufferedOutputStream(conn.getOutputStream(), 10240);
if (body.bis != null) {
byte[] buffer = new byte[10240];
for (int len; (len = body.bis.read(buffer)) != -1; ) {
bos.write(buffer, 0, len);
}
bos.close();
body.bis.close();
}
}
}
private static void trustAllHosts(HttpsURLConnection conn) {
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, DEFAULT_TRUST_MANAGERS, new java.security.SecureRandom());
conn.setSSLSocketFactory(sslContext.getSocketFactory());
conn.setHostnameVerifier(DEFAULT_VERIFIER);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void addHeader(final HttpURLConnection conn, final Map<String, String> headerMap) {
if (headerMap != null) {
for (String key : headerMap.keySet()) {
conn.setRequestProperty(key, headerMap.get(key));
}
}
}
private static boolean isSpace(final String s) {
if (s == null) return true;
for (int i = 0, len = s.length(); i < len; ++i) {
if (!Character.isWhitespace(s.charAt(i))) {
return false;
}
}
return true;
}
static String is2String(final InputStream is, final String charset) {
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
try {
for (int len; (len = is.read(buffer)) != -1; ) {
result.write(buffer, 0, len);
}
return result.toString(charset);
} catch (Exception e) {
e.printStackTrace();
return "";
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
static boolean writeFileFromIS(final File file,
final InputStream is) {
if (!createOrExistsFile(file) || is == null) return false;
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(file));
byte data[] = new byte[8192];
for (int len; (len = is.read(data)) != -1; ) {
os.write(data, 0, len);
}
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static boolean createOrExistsFile(final File file) {
if (file == null) return false;
if (file.exists()) return file.isFile();
if (!createOrExistsDir(file.getParentFile())) return false;
try {
return file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
private static boolean createOrExistsDir(final File file) {
return file != null && (file.exists() ? file.isDirectory() : file.mkdirs());
}
public static class Config {
private int connectTimeout = CONNECT_TIMEOUT_TIME;
private int readTimeout = READ_TIMEOUT_TIME;
private boolean useCaches = false;
private SSLConfig sslConfig = SSLConfig.DEFAULT_SSL_CONFIG;
private Executor workExecutor = ExecutorFactory.getDefaultWorkExecutor();
private Executor mainExecutor = ExecutorFactory.getDefaultMainExecutor();
private Proxy proxy = null;
}
static class Call implements Runnable {
private Request request;
private ResponseCallback callback;
public Call(Request request, ResponseCallback callback) {
this.request = request;
this.callback = callback;
}
@Override
public void run() {
HttpURLConnection conn = null;
try {
conn = getConnection(request);
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
InputStream is = conn.getInputStream();
callback.onResponse(new Response(conn.getHeaderFields(), is));
is.close();
} else if (responseCode == 301 || responseCode == 302) {
String location = conn.getHeaderField("Location");
call(request, callback);
} else {
String errorMsg = null;
InputStream es = conn.getErrorStream();
if (es != null) {
errorMsg = is2String(es, "utf-8");
}
callback.onFailed(new NetworkErrorException("error code: " + responseCode +
(isSpace(errorMsg) ? "" : ("\n" + "error message: " + errorMsg))));
}
} catch (IOException e) {
callback.onFailed(e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
}
}
package com.blankj.utilcode.util.http;
import java.io.IOException;
public interface Interceptor {
Response intercept(Chain chain) throws IOException;
}
package com.blankj.utilcode.util.http;
import android.support.annotation.NonNull;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.util.HashMap;
import java.util.Map;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2019/02/17
* </pre>
*/
public final class Request {
URL mURL;
Map<String, String> mHeader;
Body mBody;
public static Request withUrl(@NonNull final String url) {
return new Request(url);
}
private Request(final String url) {
try {
mURL = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
public Request addHeader(@NonNull final String name, @NonNull final String value) {
if (mHeader == null) {
mHeader = new HashMap<>();
}
mHeader.put(name, value);
return this;
}
public Request addHeader(@NonNull final Map<String, String> header) {
if (this.mHeader == null) {
this.mHeader = new HashMap<>();
}
this.mHeader.putAll(header);
return this;
}
public Request post(@NonNull final Body body) {
this.mBody = body;
return this;
}
public static class Body {
String mediaType;
BufferedInputStream bis;
long length;
private Body(final String mediaType, final byte[] body) {
this.mediaType = mediaType;
bis = new BufferedInputStream(new ByteArrayInputStream(body));
length = body.length;
}
private Body(final String mediaType, final InputStream body) {
this.mediaType = mediaType;
if (body instanceof BufferedInputStream) {
bis = (BufferedInputStream) body;
} else {
bis = new BufferedInputStream(body);
}
length = -1;
}
private static String getCharsetFromMediaType(String mediaType) {
mediaType = mediaType.toLowerCase().replace(" ", "");
int index = mediaType.indexOf("charset=");
if (index == -1) return "utf-8";
int st = index + 8;
int end = mediaType.length();
if (st >= end) {
throw new IllegalArgumentException("MediaType is not correct: \"" + mediaType + "\"");
}
for (int i = st; i < end; i++) {
char c = mediaType.charAt(i);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
if (c == '-' && i != 0) continue;
if (c == '+' && i != 0) continue;
if (c == ':' && i != 0) continue;
if (c == '_' && i != 0) continue;
if (c == '.' && i != 0) continue;
end = i;
break;
}
String charset = mediaType.substring(st, end);
return checkCharset(charset);
}
public static Body create(@NonNull String mediaType, @NonNull byte[] content) {
return new Body(mediaType, content);
}
public static Body form(@NonNull final Map<String, String> form) {
return form(form, "utf-8");
}
public static Body form(@NonNull final Map<String, String> form, String charset) {
String mediaType = "application/x-www-form-urlencoded;charset=" + checkCharset(charset);
final StringBuilder sb = new StringBuilder();
for (String key : form.keySet()) {
if (sb.length() > 0) sb.append("&");
sb.append(key).append("=").append(form.get(key));
}
try {
return new Body(mediaType, sb.toString().getBytes(charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
public static Body json(@NonNull final String json) {
return json(json, "utf-8");
}
public static Body json(@NonNull final String json, String charset) {
String mediaType = "application/json;charset=" + checkCharset(charset);
try {
return new Body(mediaType, json.getBytes(charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
// public static RequestBody file(String mediaType, final File file) {
//
// return new RequestBody(mediaType, );
// }
}
private static String checkCharset(final String charset) {
if (Charset.isSupported(charset)) return charset;
throw new IllegalCharsetNameException(charset);
}
}
package com.blankj.utilcode.util.http;
import com.google.gson.Gson;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2019/02/17
* </pre>
*/
public class Response {
private Map<String, List<String>> mHeaders;
private InputStream mBody;
public Response(Map<String, List<String>> headers, InputStream body) {
mHeaders = headers;
mBody = body;
}
public Map<String, List<String>> getHeaders() {
return mHeaders;
}
public InputStream getBody() {
return mBody;
}
public String getString() {
return getString("utf-8");
}
public String getString(final String charset) {
return HttpUtils.is2String(mBody, charset);
}
public <T> T getJson(final Type type) {
return getJson(type, "utf-8");
}
public <T> T getJson(final Type type, final String charset) {
return new Gson().fromJson(getString(charset), type);
}
public boolean downloadFile(final File file) {
return HttpUtils.writeFileFromIS(file, mBody);
}
}
package com.blankj.utilcode.util.http;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2019/02/17
* </pre>
*/
public abstract class ResponseCallback {
public abstract void onResponse(Response response);
public abstract void onFailed(Exception e);
}
package com.blankj.utilcode.util.http;
import android.annotation.SuppressLint;
import android.os.Build;
import android.support.annotation.NonNull;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509ExtendedTrustManager;
import javax.net.ssl.X509TrustManager;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2019/02/20
* </pre>
*/
public final class SSLConfig {
private SSLSocketFactory mSSLSocketFactory;
private HostnameVerifier mHostnameVerifier;
public SSLConfig(@NonNull SSLSocketFactory factory, @NonNull HostnameVerifier verifier) {
mSSLSocketFactory = factory;
mHostnameVerifier = verifier;
}
public static final HostnameVerifier DEFAULT_VERIFIER = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
public static final SSLSocketFactory DEFAULT_SSL_SOCKET_FACTORY = new DefaultSSLSocketFactory();
public static final SSLConfig DEFAULT_SSL_CONFIG = new SSLConfig(DEFAULT_SSL_SOCKET_FACTORY, DEFAULT_VERIFIER);
private static class DefaultSSLSocketFactory extends SSLSocketFactory {
private static final String[] PROTOCOL_ARRAY;
private static final TrustManager[] DEFAULT_TRUST_MANAGERS;
static {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
PROTOCOL_ARRAY = new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"};
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
PROTOCOL_ARRAY = new String[]{"SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"};
} else {
PROTOCOL_ARRAY = new String[]{"SSLv3", "TLSv1"};
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
DEFAULT_TRUST_MANAGERS = new TrustManager[]{
new X509ExtendedTrustManager() {
@SuppressLint("TrustAllX509TrustManager")
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) { /**/ }
@SuppressLint("TrustAllX509TrustManager")
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) { /**/ }
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
@SuppressLint("TrustAllX509TrustManager")
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) { /**/ }
@SuppressLint("TrustAllX509TrustManager")
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) { /**/ }
@SuppressLint("TrustAllX509TrustManager")
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) { /**/ }
@SuppressLint("TrustAllX509TrustManager")
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) { /**/ }
}
};
} else {
DEFAULT_TRUST_MANAGERS = new TrustManager[]{
new X509TrustManager() {
@SuppressLint("TrustAllX509TrustManager")
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) { /**/ }
@SuppressLint("TrustAllX509TrustManager")
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) { /**/ }
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
};
}
}
private SSLSocketFactory mFactory;
DefaultSSLSocketFactory() {
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, DEFAULT_TRUST_MANAGERS, new SecureRandom());
mFactory = sslContext.getSocketFactory();
} catch (GeneralSecurityException e) {
throw new AssertionError();
}
}
@Override
public String[] getDefaultCipherSuites() {
return mFactory.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return mFactory.getSupportedCipherSuites();
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
Socket ssl = mFactory.createSocket(s, host, port, autoClose);
setSupportProtocolAndCipherSuites(ssl);
return ssl;
}
@Override
public Socket createSocket(String host, int port) throws IOException {
Socket ssl = mFactory.createSocket(host, port);
setSupportProtocolAndCipherSuites(ssl);
return ssl;
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
Socket ssl = mFactory.createSocket(host, port, localHost, localPort);
setSupportProtocolAndCipherSuites(ssl);
return ssl;
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
Socket ssl = mFactory.createSocket(host, port);
setSupportProtocolAndCipherSuites(ssl);
return ssl;
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
Socket ssl = mFactory.createSocket(address, port, localAddress, localPort);
setSupportProtocolAndCipherSuites(ssl);
return ssl;
}
@Override
public Socket createSocket() throws IOException {
Socket ssl = mFactory.createSocket();
setSupportProtocolAndCipherSuites(ssl);
return ssl;
}
private void setSupportProtocolAndCipherSuites(Socket socket) {
if (socket instanceof SSLSocket) {
((SSLSocket) socket).setEnabledProtocols(PROTOCOL_ARRAY);
}
}
}
}
......@@ -10,7 +10,7 @@ import org.robolectric.shadows.ShadowLog;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
/**
* <pre>
......@@ -31,6 +31,38 @@ public class BaseTest {
@Test
public void test() throws Exception {
final Scanner scanner = new Scanner(System.in);
final CountDownLatch countDownLatch = new CountDownLatch(1);
final Future<?> submit = ThreadUtils.getSinglePool().submit(new Runnable() {
@Override
public void run() {
System.out.println("haha0");
scanner.nextLine();
System.out.println("haha");
if (Thread.currentThread().isInterrupted()) {
System.out.println(1);
}
for (int i = 0; i < 1000000; i++) {
if (Thread.currentThread().isInterrupted()) {
break;
}
// try {
// Thread.sleep(100);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
System.out.println(i);
}
}
});
Thread.sleep(500);
scanner.close();
Thread.sleep(500);
submit.cancel(true);
countDownLatch.await();
// final CountDownLatch countDownLatch = new CountDownLatch(1);
// final Scanner scanner = new Scanner(System.in);
// ExecutorService singlePool = ThreadUtils.getSinglePool();
......
package com.blankj.utilcode.util.http;
import com.blankj.utilcode.util.BaseTest;
import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.TestConfig;
import com.blankj.utilcode.util.TimeUtils;
import org.junit.Test;
import java.io.File;
import java.util.List;
/**
* <pre>
......@@ -24,56 +14,56 @@ public class HttpUtilsTest extends BaseTest {
private static final String BASE_URL = "http://127.0.0.1:8081";
@Test
public void getString() {
HttpUtils.call(Request.withUrl(BASE_URL + "/listUsers"), new ResponseCallback() {
@Override
public void onResponse(Response response) {
System.out.println(response.getHeaders());
System.out.println(response.getString());
}
@Override
public void onFailed(Exception e) {
e.printStackTrace();
}
});
}
@Test
public void getJson() {
HttpUtils.call(Request.withUrl(BASE_URL + "/listUsers"), new ResponseCallback() {
@Override
public void onResponse(Response response) {
System.out.println(response.getHeaders());
List<UserBean> users = response.getJson(GsonUtils.getListType(UserBean.class));
System.out.println(GsonUtils.toJson(users));
}
@Override
public void onFailed(Exception e) {
e.printStackTrace();
}
});
}
@Test
public void downloadFile() {
HttpUtils.call(Request.withUrl(BASE_URL + "/listUsers"), new ResponseCallback() {
@Override
public void onResponse(Response response) {
System.out.println(response.getHeaders());
File file = new File(TestConfig.PATH_HTTP + TimeUtils.getNowMills());
response.downloadFile(file);
System.out.println(FileIOUtils.readFile2String(file));
FileUtils.delete(file);
}
@Override
public void onFailed(Exception e) {
e.printStackTrace();
}
});
}
// @Test
// public void getString() {
// HttpUtils.call(Request.withUrl(BASE_URL + "/listUsers"), new ResponseCallback() {
// @Override
// public void onResponse(Response response) {
// System.out.println(response.getHeaders());
// System.out.println(response.getString());
// }
//
// @Override
// public void onFailed(Exception e) {
// e.printStackTrace();
// }
// });
// }
//
// @Test
// public void getJson() {
// HttpUtils.call(Request.withUrl(BASE_URL + "/listUsers"), new ResponseCallback() {
// @Override
// public void onResponse(Response response) {
// System.out.println(response.getHeaders());
// List<UserBean> users = response.getJson(GsonUtils.getListType(UserBean.class));
// System.out.println(GsonUtils.toJson(users));
// }
//
// @Override
// public void onFailed(Exception e) {
// e.printStackTrace();
// }
// });
// }
//
// @Test
// public void downloadFile() {
// HttpUtils.call(Request.withUrl(BASE_URL + "/listUsers"), new ResponseCallback() {
// @Override
// public void onResponse(Response response) {
// System.out.println(response.getHeaders());
// File file = new File(TestConfig.PATH_HTTP + TimeUtils.getNowMills());
// response.downloadFile(file);
// System.out.println(FileIOUtils.readFile2String(file));
// FileUtils.delete(file);
// }
//
// @Override
// public void onFailed(Exception e) {
// e.printStackTrace();
// }
// });
// }
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册