List of usage examples for javax.net.ssl HttpsURLConnection connect
public abstract void connect() throws IOException;
From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPSConnectionAndTrustConfirmationIT.java
@Test public void testTrustConfirmationAddDeleteCertificateDirectly() throws CMException, IOException, CertificateException { // Initially trust provider list is empty, we only verify by what is in // Credential Manager's Truststore (and it does not contains the certificate for https://heater.cs.man.ac.uk:7443/) // Do not forget to initialise Taverna's/Credential Manager's SSLSocketFactory credentialManager.initializeSSL();/*from ww w . j ava2 s. c om*/ URL url = new URL("https://heater.cs.man.ac.uk:7443/"); HttpsURLConnection conn; conn = (HttpsURLConnection) url.openConnection(); try { // This should fail conn.connect(); fail("Connection to https://heater.cs.man.ac.uk:7443/ should be untrusted at this point."); } catch (SSLHandshakeException sslex) { // expected to fail so all is good } finally { conn.disconnect(); } // Add heater's certificate directly to Credential Manager's Truststore // Load the test trusted certificate (belonging to heater.cs.man.ac.uk) X509Certificate trustedCertficate; URL trustedCertficateFileURL = getClass().getResource("/security/tomcat_heater_certificate.pem"); System.out.println("testTrustConfirmationAddDeleteCertificateDirectly: trusted certficate file URL " + trustedCertficateFileURL); File trustedCertFile = new File(trustedCertficateFileURL.getPath()); FileInputStream inStream = new FileInputStream(trustedCertFile); //InputStream inStream = getClass().getClassLoader().getResourceAsStream("security/tomcat_heater_certificate.pem"); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); trustedCertficate = (X509Certificate) certFactory.generateCertificate(inStream); try { inStream.close(); } catch (Exception e) { // Ignore } String alias = credentialManager.addTrustedCertificate(trustedCertficate); HttpsURLConnection conn2 = (HttpsURLConnection) url.openConnection(); // This should work now conn2.connect(); //System.out.println(conn2.getHeaderField(0)); assertEquals("HTTP/1.1 200 OK", conn2.getHeaderField(0)); conn2.disconnect(); // Now remove certificate and see if the "trust" changes credentialManager.deleteTrustedCertificate(alias); HttpsURLConnection conn3; conn3 = (HttpsURLConnection) url.openConnection(); try { // This should fail conn3.connect(); fail("Connection to https://heater.cs.man.ac.uk:7443/ should be untrusted at this point."); } catch (SSLHandshakeException sslex) { // expected to fail so all is good } finally { conn3.disconnect(); } }
From source file:com.kaixin.connect.Util.java
/** * http/*w w w .ja v a2 s .co m*/ * * @param context * * @param requestURL * * @param httpMethod * GET POST * @param params * key-valuekeyvalueStringbyte[] * @param photos * key-value keyfilename * valueInputStreambyte[] * InputStreamopenUrl * @return JSON * @throws IOException */ public static String openUrl(Context context, String requestURL, String httpMethod, Bundle params, Map<String, Object> photos) throws IOException { OutputStream os; if (httpMethod.equals("GET")) { requestURL = requestURL + "?" + encodeUrl(params); } URL url = new URL(requestURL); HttpsURLConnection conn = (HttpsURLConnection) getConnection(context, url); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " KaixinAndroidSDK"); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Charsert", "UTF-8"); if (!httpMethod.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { if (params.getByteArray(key) != null) { dataparams.putByteArray(key, params.getByteArray(key)); } } String BOUNDARY = Util.md5(String.valueOf(System.currentTimeMillis())); // String endLine = "\r\n"; conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + BOUNDARY + endLine).getBytes()); os.write((encodePostBody(params, BOUNDARY)).getBytes()); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; name=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } } if (photos != null && !photos.isEmpty()) { for (String key : photos.keySet()) { Object obj = photos.get(key); if (obj instanceof InputStream) { InputStream is = (InputStream) obj; try { os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes()); byte[] data = new byte[UPLOAD_BUFFER_SIZE]; int nReadLength = 0; while ((nReadLength = is.read(data)) != -1) { os.write(data, 0, nReadLength); } os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } finally { try { if (null != is) { is.close(); } } catch (Exception e) { Log.e(LOG_TAG, "Exception on closing input stream", e); } } } else if (obj instanceof byte[]) { byte[] byteArray = (byte[]) obj; os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine) .getBytes()); os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes()); os.write(byteArray); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } else { Log.e(LOG_TAG, ""); } } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { response = read(conn.getErrorStream()); } return response; }
From source file:com.ds.kaixin.Util.java
/** * http//from w w w.j a v a 2 s . c o m * * @param context * * @param requestURL * * @param httpMethod * GET POST * @param params * key-valuekeyvalueString * byte[] * @param photos * key-value keyfilename * valueInputStreambyte[] * InputStreamopenUrl * @return JSON * @throws IOException */ public static String openUrl(Context context, String requestURL, String httpMethod, Bundle params, Map<String, Object> photos) throws IOException { OutputStream os; if (httpMethod.equals("GET")) { requestURL = requestURL + "?" + encodeUrl(params); } URL url = new URL(requestURL); HttpsURLConnection conn = (HttpsURLConnection) getConnection(context, url); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " KaixinAndroidSDK"); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Charsert", "UTF-8"); if (!httpMethod.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { if (params.getByteArray(key) != null) { dataparams.putByteArray(key, params.getByteArray(key)); } } String BOUNDARY = Util.md5(String.valueOf(System.currentTimeMillis())); // String endLine = "\r\n"; conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + BOUNDARY + endLine).getBytes()); os.write((encodePostBody(params, BOUNDARY)).getBytes()); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; name=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } } if (photos != null && !photos.isEmpty()) { for (String key : photos.keySet()) { Object obj = photos.get(key); if (obj instanceof InputStream) { InputStream is = (InputStream) obj; try { os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes()); byte[] data = new byte[UPLOAD_BUFFER_SIZE]; int nReadLength = 0; while ((nReadLength = is.read(data)) != -1) { os.write(data, 0, nReadLength); } os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } finally { try { if (null != is) { is.close(); } } catch (Exception e) { Log.e(LOG_TAG, "Exception on closing input stream", e); } } } else if (obj instanceof byte[]) { byte[] byteArray = (byte[]) obj; os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine) .getBytes()); os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes()); os.write(byteArray); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } else { Log.e(LOG_TAG, ""); } } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { response = read(conn.getErrorStream()); } return response; }
From source file:com.example.onenoteservicecreatepageexample.SendRefreshTokenAsyncTask.java
private Object[] attemptRefreshAccessToken(String refreshToken) throws Exception { /**//from w w w.j av a2s . c o m * A new connection to the endpoint that processes requests for refreshing the access token */ HttpsURLConnection refreshTokenConnection = (HttpsURLConnection) (new URL(MSA_TOKEN_REFRESH_URL)) .openConnection(); refreshTokenConnection.setDoOutput(true); refreshTokenConnection.setRequestMethod("POST"); refreshTokenConnection.setDoInput(true); refreshTokenConnection.setRequestProperty("Content-Type", TOKEN_REFRESH_CONTENT_TYPE); refreshTokenConnection.connect(); OutputStream refreshTokenRequestStream = null; try { refreshTokenRequestStream = refreshTokenConnection.getOutputStream(); String requestBody = MessageFormat.format(TOKEN_REFRESH_REQUEST_BODY, Constants.CLIENTID, TOKEN_REFRESH_REDIRECT_URL, refreshToken); refreshTokenRequestStream.write(requestBody.getBytes()); refreshTokenRequestStream.flush(); } finally { if (refreshTokenRequestStream != null) { refreshTokenRequestStream.close(); } } if (refreshTokenConnection.getResponseCode() == 200) { return parseRefreshTokenResponse(refreshTokenConnection); } else { throw new Exception("The attempt to refresh the access token failed"); } }
From source file:org.croudtrip.activities.MainActivity.java
public void showUserInfoInNavigationDrawer() { // Get logged-in user and his data User user = AccountManager.getLoggedInUser(getApplicationContext()); String firstName = (user == null || user.getFirstName() == null) ? "" : user.getFirstName(); String lastName = (user == null || user.getLastName() == null) ? "" : user.getLastName(); String email = (user == null || user.getEmail() == null) ? "" : user.getEmail(); final String avatarUrl = (user == null || user.getAvatarUrl() == null) ? null : user.getAvatarUrl(); Timber.i("Nav drawer avatarUrl is: " + avatarUrl); final MaterialAccount account = new MaterialAccount(this.getResources(), firstName + " " + lastName, email, R.drawable.profile, R.drawable.background_drawer); this.addAccount(account); // Download his avatar if (avatarUrl != null) { Observable.defer(new Func0<Observable<Bitmap>>() { @Override// w w w . ja v a 2 s.co m public Observable<Bitmap> call() { try { URL url = new URL(avatarUrl); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); return Observable.just(BitmapFactory.decodeStream(input)); } catch (Exception e) { return Observable.error(e); } } }).compose(new DefaultTransformer<Bitmap>()).subscribe(new Action1<Bitmap>() { @Override public void call(Bitmap avatar) { Timber.d("avatar is null " + (avatar == null)); Timber.d("" + avatar.getWidth()); account.setPhoto(avatar); notifyAccountDataChanged(); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { Timber.e(throwable, "failed to download avatar"); } }); } }
From source file:com.google.android.apps.picview.request.CachedWebRequestFetcher.java
/** * Fetches the given URL from the web./*from w w w. ja v a 2 s . c om*/ */ public String fetchFromWeb(URL url) { Log.d(TAG, "Fetching from web: " + url.toString()); HttpsURLConnection conn = null; HttpResponse resp = null; try { conn = (HttpsURLConnection) url.openConnection(); conn.setUseCaches(false); conn.setReadTimeout(30000); // 30 seconds. conn.setDoInput(true); conn.addRequestProperty("GData-Version", "2"); conn.connect(); InputStream is = conn.getInputStream(); return readStringFromStream(is); } catch (Exception e) { Log.v(TAG, readStringFromStream(conn.getErrorStream())); e.printStackTrace(); } return null; }
From source file:xin.nic.sdk.registrar.util.HttpUtil.java
/** * ??HTTPS GET// w w w . j a v a2 s .c o m * * @param url URL * @return */ public static HttpResp doHttpsGet(URL url) { HttpsURLConnection conn = null; InputStream inputStream = null; Reader reader = null; try { // ???httphttps String protocol = url.getProtocol(); if (!PROTOCOL_HTTPS.equals(protocol)) { throw new XinException("xin.error.url", "?https"); } // conn = (HttpsURLConnection) url.openConnection(); SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, tmArr, new SecureRandom()); conn.setSSLSocketFactory(sc.getSocketFactory()); // ? conn.setConnectTimeout(connTimeout); conn.setReadTimeout(readTimeout); conn.setDoOutput(true); conn.setDoInput(true); // UserAgent conn.setRequestProperty("User-Agent", "java-sdk"); // ? conn.connect(); // ? inputStream = conn.getInputStream(); reader = new InputStreamReader(inputStream, charset); BufferedReader bufferReader = new BufferedReader(reader); StringBuilder stringBuilder = new StringBuilder(); String inputLine = ""; while ((inputLine = bufferReader.readLine()) != null) { stringBuilder.append(inputLine); stringBuilder.append("\n"); } // HttpResp resp = new HttpResp(); resp.setStatusCode(conn.getResponseCode()); resp.setStatusPhrase(conn.getResponseMessage()); resp.setContent(stringBuilder.toString()); // return resp; } catch (MalformedURLException e) { throw new XinException("xin.error.url", "url:" + url + ", url?"); } catch (IOException e) { throw new XinException("xin.error.http", String.format("IOException:%s", e.getMessage())); } catch (KeyManagementException e) { throw new XinException("xin.error.url", "url:" + url + ", url?"); } catch (NoSuchAlgorithmException e) { throw new XinException("xin.error.url", "url:" + url + ", url?"); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { throw new XinException("xin.error.url", "url:" + url + ", reader"); } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { throw new XinException("xin.error.url", "url:" + url + ", ?"); } } // quietClose(conn); } }
From source file:cn.bidaround.ytcore.kaixin.KaixinUtil.java
/** * ??http//from w w w .j a v a 2 s.com * * @param context * * @param requestURL * ?? * @param httpMethod * GET POST * @param params * key-value??key???value???Stringbyte[] * @param photos * key-value??? keyfilename * value????InputStreambyte[] * ?InputStreamopenUrl? * @return ?JSON * @throws IOException */ public static String openUrl(Context context, String requestURL, String httpMethod, Bundle params, Map<String, Object> photos) throws IOException { OutputStream os; if (httpMethod.equals("GET")) { requestURL = requestURL + "?" + encodeUrl(params); } URL url = new URL(requestURL); HttpsURLConnection conn = (HttpsURLConnection) getConnection(context, url); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " KaixinAndroidSDK"); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Charsert", "UTF-8"); if (!httpMethod.equals("GET")) { Bundle dataparams = new Bundle(); // for (String key : params.keySet()) { // if (params.getByteArray(key) != null) { // dataparams.putByteArray(key, params.getByteArray(key)); // } // } String BOUNDARY = KaixinUtil.md5(String.valueOf(System.currentTimeMillis())); // ? String endLine = "\r\n"; conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + BOUNDARY + endLine).getBytes()); os.write((encodePostBody(params, BOUNDARY)).getBytes()); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; name=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } } if (photos != null && !photos.isEmpty()) { for (String key : photos.keySet()) { Object obj = photos.get(key); if (obj instanceof InputStream) { InputStream is = (InputStream) obj; try { os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes()); byte[] data = new byte[UPLOAD_BUFFER_SIZE]; int nReadLength = 0; while ((nReadLength = is.read(data)) != -1) { os.write(data, 0, nReadLength); } os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } finally { try { if (null != is) { is.close(); } } catch (Exception e) { Log.e(LOG_TAG, "Exception on closing input stream", e); } } } else if (obj instanceof byte[]) { byte[] byteArray = (byte[]) obj; os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine) .getBytes()); os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes()); os.write(byteArray); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } else { Log.e(LOG_TAG, "?"); } } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { response = read(conn.getErrorStream()); } return response; }
From source file:io.fabric8.apiman.BearerTokenFilter.java
/** * Validates the bearer token with the kubernetes oapi and returns the username * if it is a valid token.// ww w . j a v a 2 s . c o m * * @param bearerHeader * @return username of the user to whom the token was issued to * @throws IOException - when the token is invalid, or oapi cannot be reached. */ protected String validateBearerToken(String bearerHeader) throws IOException { ObjectMapper mapper = new ObjectMapper(); HttpsURLConnection con = (HttpsURLConnection) kubernetesOsapiUrl.openConnection(); con.setRequestProperty("Authorization", bearerHeader); con.setConnectTimeout(10000); con.setReadTimeout(10000); con.setRequestProperty("Content-Type", "application/json"); if (kubernetesTrustCert) TrustEverythingSSLTrustManager.trustAllSSLCertificates(con); con.connect(); OAuthClientAuthorizationList userList = mapper.readValue(con.getInputStream(), OAuthClientAuthorizationList.class); String userName = userList.getItems().get(0).getMetadata().getName(); return userName; }
From source file:com.glaf.core.util.http.HttpUtils.java
/** * ?https?//from ww w .jav a 2 s . c o m * * @param requestUrl * ? * @param method * ?GET?POST * @param content * ??? * @return */ public static String doRequest(String requestUrl, String method, String content, boolean isSSL) { log.debug("requestUrl:" + requestUrl); HttpsURLConnection conn = null; InputStream inputStream = null; BufferedReader bufferedReader = null; InputStreamReader inputStreamReader = null; StringBuffer buffer = new StringBuffer(); try { URL url = new URL(requestUrl); conn = (HttpsURLConnection) url.openConnection(); if (isSSL) { // SSLContext?? TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // SSLContextSSLSocketFactory SSLSocketFactory ssf = sslContext.getSocketFactory(); conn.setSSLSocketFactory(ssf); } conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); // ?GET/POST conn.setRequestMethod(method); if ("GET".equalsIgnoreCase(method)) { conn.connect(); } // ???? if (StringUtils.isNotEmpty(content)) { OutputStream outputStream = conn.getOutputStream(); // ???? outputStream.write(content.getBytes("UTF-8")); outputStream.flush(); outputStream.close(); } // ??? inputStream = conn.getInputStream(); inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } log.debug("response:" + buffer.toString()); } catch (ConnectException ce) { ce.printStackTrace(); log.error(" http server connection timed out."); } catch (Exception ex) { ex.printStackTrace(); log.error("http request error:{}", ex); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(bufferedReader); IOUtils.closeQuietly(inputStreamReader); if (conn != null) { conn.disconnect(); } } return buffer.toString(); }