AndroidManifest.xml 中 application节点中配置明文,可以用http地址 android:usesCleartextTraffic="true" 否则http请求发不出去,只能用https
1、新TrustAllcert类实现X509TrustManager接口:
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
public class TrustAllCerts implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {}
@Override
public X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];}
}
复制代码
2、初始化OKHttpClient配置
OkHttpClient okHttpClient = null;
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(timeout, TimeUnit.SECONDS);//响应时间
builder.readTimeout(timeout, TimeUnit.SECONDS);//读取时间
// 信任https证书
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
//创建管理器
TrustAllCerts trustAllCerts = new TrustAllCerts();
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{trustAllCerts}, new SecureRandom());
//为OkHttpClient设置sslSocketFactory
builder.sslSocketFactory(sslContext.getSocketFactory(), trustAllCerts);
okHttpClient = builder.build();
} catch (Exception e) {
e.printStackTrace();
}
得到的okHttpClient,信任所有的https。
使用,build.gradle中配置 implementation("com.squareup.okhttp3:okhttp:3.12.1")
发送请求示例:
private static final MediaType JSON = MediaType.get("application/json;charset=utf-8;");
public String postJsonSync(String url, String json, Map<String,String> requestHeaderMap, Integer timeout) throws Exception {
try {
String data = json;
Headers headers = null;
okhttp3.Headers.Builder headersbuilder = new okhttp3.Headers.Builder();
if(requestHeaderMap != null && requestHeaderMap.size() >0){
for (String key:requestHeaderMap.keySet()){
headersbuilder.add(key, requestHeaderMap.get(key));
}
}
headers = headersbuilder.build();
RequestBody body = RequestBody.create(JSON, data);
Request request;
request = new Request.Builder()
.url(url)
.headers(headers)
.post(body)
.build();
OkHttpClient okHttpClient = getOkHttpClient(timeout);
Response response = okHttpClient.newCall(request).execute();
String rets = response.body().string();return rets;
}catch (Exception ex){throw ex;
}
}
getOkHttpClient(timeOut)就是最上面获取okHttpClient的代码。
OKHttp下载文件
import java.io.File;
public interface AppDownloadCallBack {
void onDownloading(int progress);
void onDownloadSuccess(File file);
void onDownloadFailed(Exception e);
}
/**
* 文件下载
*
* @param url 下载路径
* @param destFileDir 下载的文件储存目录
* @param timeout 超时时间,单位秒
* @param destFileName 下载文件名称,后面记得拼接后缀,否则手机没法识别文件类型
* @return
*/
public boolean downloadFile(String url, String destFileDir, String destFileName, Integer timeout, AppDownloadCallBack listener) throws IOException {
Request request = new Request.Builder().url(url).build();
Response response = null;
OkHttpClient okHttpClient = getOkHttpClient(timeout);
response = okHttpClient.newCall(request).execute();
boolean result;
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
//储存下载文件的目录
File dir = new File(destFileDir);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, destFileName);
try {
is = response.body().byteStream();
long total = response.body().contentLength();
fos = new FileOutputStream(file);
long sum = 0;
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
sum += len;
int progress = (int) (sum * 1.0f / total * 100);
//下载中更新进度条
if (listener != null) {
listener.onDownloading(progress);
}
}
fos.flush();
result = true;
slog.i("downloadFile", "下载完成");
//下载完成
if (listener != null) {
listener.onDownloadSuccess(file);
}
} catch (Exception e) {
if (listener != null) {
listener.onDownloadFailed(e);
}
result = false;
slog.e("downloadFile", e);
} finally {
try {
if (is != null) {
is.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
}
}
return result;
}