我正在尝试使用ssl将文件上传到某个URL.我使用此代码设置信任管理器 -
public static void trustAll () { TrustManage[] trustEverythingTrustManager = new TrustManager[] { new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } public X509Certificate[] getAcceptedIssuers() { // TODO Auto-generated method stub return null; } } }; SSLContext sc; try { sc = SSLContext.getInstance("TLS"); sc.init(null, trustEverythingTrustManager, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { } }
这一个设置主机名验证 -
public static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } };
然后我打开这样的连接 -
URL url = new URL("some_url"); HttpURLConnection connection = null; // check if this is https or just http if (url.getProtocol().toLowerCase().equals("https")) { trustAll(); HttpsURLConnection https = (HttpsURLConnection) url.openConnection(); https.setHostnameVerifier(DO_NOT_VERIFY); connection = https; } else { connection = (HttpURLConnection) url.openConnection(); }
在我获得连接后,我使用它来上传数据.我使用http一切正常但是当我尝试https时我得到以下异常 -
写入错误:系统调用期间的I/O错误,断开管道java.io.IOException:写入错误:系统调用期间的I/O错误,org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.nativewrite中的管道损坏(本机方法)org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.access $ 600(OpenSSLSocketImpl.java:55)at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl $ SSLOutputStream.write(OpenSSLSocketImpl.java:565 )java的org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection $ HttpOutputStream.write(HttpURLConnection.java:652)中的java.io.OutputStream.write(OutputStream.java:82). io.DataOutputStream.write(DataOutputStream.java:101)
奇怪的是,我不会一直得到例外.当我尝试上传小文件(200K)它工作正常或它崩溃非常罕见,但当我尝试上传更大的(超过1MB)我几乎每次都得到异常.
有任何想法吗 ?