这是我的代码:
private void upload() {
Task task = new Task();
task.execute();
}
class Task extends AsyncTask<String, String, String> {
@SuppressLint("NewApi")
@Override
protected String doInBackground(String... params) {
try {
URL mUrl = new URL(HttpUrls.getUrl() + HttpUrls.UPLOAD_IMAGE);
SSLContext sslContext = Global.getSSLContext(AppConfig.getApplicationContext());
HttpsURLConnection conn = (HttpsURLConnection) mUrl
.openConnection(); conn.setDefaultHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
conn.setSSLSocketFactory(sslContext.getSocketFactory());
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty(Constants.Field.USER_UUID, mProductUuid);
conn.setRequestProperty(Constants.Field.IMG_TYPE, IMGType.PDT_IMG.name());
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
OutputStream output = conn.getOutputStream();
if (StringUtils.isEmpty2(mImgPath)) {
output.write(begin(System.currentTimeMillis() + ".jpg"));
} else {
output.write(begin(mImgPath));
}
if (mUri != null) {
Bitmap bitmap = ImageFactory.getBitmapFormUri(GalleryActivity.this, mUri, true);
output.write(ImageFactory.bitmapToByteAAA(bitmap));
try {
bitmap.recycle();
} catch (Exception e) {
}finally{
if(bitmap!=null && !bitmap.isRecycled()){
bitmap.recycle();
bitmap = null;
}
}
} else {
output.write(ImageFactory.bitmapToByteBBB(mBitmap));
}
output.write(end());
output.flush();
output.close();
return IOUtils.toString(conn.getInputStream());
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
我在服务器中使用自定义证书,我在Gloabal.getSSLContext(Application.getApplicationContext())
中加载了trust.bks,每次单击上传按钮时都会调用upload()方法。
但奇怪的是,当我第一次点击上传按钮时,我收到错误“主机名未经验证”,这意味着我的代码中的conn.setDefaultHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
不起作用,当我点击上传按钮时第二次,它运作良好,我成功上传文件,为什么?当我调用setDefaultHostnameVerifier()时是否有任何延迟?如果是,我怎么能让它第一次调用upload()方法?任何人都可以告诉我setDefaultHostnameVerifier()方法的原理吗?