List of usage examples for javax.net.ssl HttpsURLConnection setInstanceFollowRedirects
public void setInstanceFollowRedirects(boolean followRedirects)
From source file:in.rab.ordboken.NeClient.java
private String fetchMainSitePage(String pageUrl) throws IOException, LoginException, ParserException { URL url = new URL(pageUrl); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setInstanceFollowRedirects(false); urlConnection.connect();//from w w w. ja va 2 s .c o m int response; try { response = urlConnection.getResponseCode(); } catch (IOException e) { urlConnection.disconnect(); throw e; } if (response == 302) { urlConnection.disconnect(); try { loginMainSite(); } catch (EOFException e) { // Same EOFException as on token refreshes. Seems to be a POST thing. loginMainSite(); } url = new URL(pageUrl); urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setInstanceFollowRedirects(false); urlConnection.connect(); try { response = urlConnection.getResponseCode(); } catch (IOException e) { urlConnection.disconnect(); throw e; } } try { if (response != 200) { throw new ParserException("Unable to get page: " + response); } return inputStreamToString(urlConnection.getInputStream()); } finally { urlConnection.disconnect(); } }
From source file:org.openhab.binding.unifi.internal.UnifiBinding.java
private void logout() { URL url = null;/* ww w . ja v a 2 s. c o m*/ if (cookies.size() == 0) return; try { url = new URL(getControllerUrl("api/logout")); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Cookie", cookies.get(0) + "; " + cookies.get(1)); connection.getInputStream(); } catch (MalformedURLException e) { logger.error("The URL '" + url + "' is malformed: " + e.toString()); } catch (Exception e) { logger.error("Cannot do logout. Exception: " + e.toString()); } }
From source file:org.openhab.binding.unifi.internal.UnifiBinding.java
private String sendToController(String url, String urlParameters, String method) { try {/*from w w w .j a va 2 s .c o m*/ synchronized (cookies) { byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); URL cookieUrl = new URL(url); HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection(); connection.setInstanceFollowRedirects(true); connection.setRequestMethod(method); //for(String cookie : cookies) { connection.setRequestProperty("Cookie", cookies.get(0) + "; " + cookies.get(1)); //} if (urlParameters.length() > 0) { connection.setDoOutput(true); connection.setRequestProperty("Content-Length", Integer.toString(postData.length)); connection.setUseCaches(false); try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { wr.write(postData); } } InputStream response = connection.getInputStream(); String line = readResponse(response); if (!checkResponse(line)) { logger.error("Unifi response: " + line); } return line; } } catch (MalformedURLException e) { logger.error("The URL '" + url + "' is malformed: " + e.toString()); } catch (Exception e) { logger.error("Cannot send data " + urlParameters + " to url " + url + ". Exception: " + e.toString()); } return ""; }
From source file:org.openhab.binding.unifi.internal.UnifiBinding.java
private boolean login() { String url = null;/*ww w. jav a 2s . c o m*/ try { url = getControllerUrl("api/login"); String urlParameters = "{'username':'" + username + "','password':'" + password + "'}"; byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); URL cookieUrl = new URL(url); HttpsURLConnection connection = (HttpsURLConnection) cookieUrl.openConnection(); connection.setDoOutput(true); connection.setInstanceFollowRedirects(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Referer", getControllerUrl("login")); connection.setRequestProperty("Content-Length", Integer.toString(postData.length)); connection.setUseCaches(false); try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { wr.write(postData); } //get cookie cookies.clear(); String headerName; for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) { if (headerName.equals("Set-Cookie")) { cookies.add(connection.getHeaderField(i)); } } InputStream response = connection.getInputStream(); String line = readResponse(response); logger.debug("Unifi response: " + line); return checkResponse(line); } catch (MalformedURLException e) { logger.error("The URL '" + url + "' is malformed: " + e.toString()); } catch (Exception e) { logger.error("Cannot get Ubiquiti Unifi login cookie: " + e.toString()); } return false; }
From source file:org.openhab.binding.zonky.internal.ZonkyBinding.java
private void setupConnectionDefaults(HttpsURLConnection connection) { connection.setRequestProperty("User-Agent", USER_AGENT); connection.setRequestProperty("Accept-Language", "cs-CZ"); //connection.setRequestProperty("Accept-Encoding", "gzip, deflate"); connection.setRequestProperty("Accept", "application/json, text/plain, */*"); connection.setRequestProperty("Referer", "https://app.zonky.cz/"); connection.setInstanceFollowRedirects(false); connection.setUseCaches(false);//from w ww.ja va2 s . co m }
From source file:iracing.webapi.IracingWebApi.java
/** * /*from ww w. j a va2 s .c o m*/ * @return a login response code * @throws IOException * @throws LoginException * @see #LOGIN_RESPONSE_SUCCESS * @see #LOGIN_RESPONSE_CONNECTION_ERROR * @see #LOGIN_RESPONSE_DOWN_FOR_MAINTAINENCE * @see #LOGIN_RESPONSE_FAILED_CREDENTIALS */ public LoginResponse login() throws IOException, LoginException { try { installCerts(); } catch (Exception e1) { e1.printStackTrace(); throw new LoginException("error whilst attempting to install SSL certificates"); } System.setProperty("javax.net.ssl.trustStore", "jssecacerts"); System.setProperty("javax.net.ssl.trustStorePassword", CERT_STORE_PASSWORD); if (loginRequiredHandler == null) return LoginResponse.ConfigError; IracingLoginCredentials creds = new IracingLoginCredentials(); if (!loginRequiredHandler.onLoginCredentialsRequired(creds)) return LoginResponse.CredentialsError; String encodedUsername = URLEncoder.encode(creds.getEmailAddress(), "UTF-8"); String encodedPW = URLEncoder.encode(creds.getPassword(), "UTF-8"); String urltext = LOGIN_URL + "?username=" + encodedUsername + "&password=" + encodedPW; // + "&utcoffset=-60&todaysdate="; URL url = new URL(urltext); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.addRequestProperty("Content-Length", "0"); conn.setInstanceFollowRedirects(false); HttpsURLConnection.setFollowRedirects(false); try { conn.connect(); } catch (Exception e) { e.printStackTrace(); throw new LoginException(e.getMessage()); } if (isMaintenancePage(conn)) return LoginResponse.DownForMaintenance; String headerName; for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) { if (headerName.equalsIgnoreCase(SET_COOKIE)) { addToCookieMap(conn.getHeaderField(i)); } else { if (!headerName.equals("Location")) { continue; } String location2 = conn.getHeaderField(i); if (location2.indexOf("failedlogin") != -1) { throw new LoginException("You have been directed to the failed login page"); } } } createCookieFromMap(); conn.disconnect(); return LoginResponse.Success; }
From source file:org.globusonline.nexus.BaseNexusRestClient.java
/** * @param path/* w ww . j av a 2 s . com*/ * @return JSON Response from action * @throws NexusClientException */ protected JSONObject issueRestRequest(String path, String httpMethod, String contentType, String accept, JSONObject params, NexusAuthenticator auth) throws NexusClientException { JSONObject json = null; HttpsURLConnection connection; if (httpMethod.isEmpty()) { httpMethod = "GET"; } if (contentType.isEmpty()) { contentType = "application/json"; } if (accept.isEmpty()) { accept = "application/json"; } int responseCode; try { URL url = new URL(getNexusApiUrl() + path); connection = (HttpsURLConnection) url.openConnection(); if (ignoreCertErrors) { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); connection.setSSLSocketFactory(sc.getSocketFactory()); connection.setHostnameVerifier(allHostsValid); } if (auth != null) { auth.authenticate(connection); } connection.setDoOutput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod(httpMethod); connection.setRequestProperty("Content-Type", contentType); connection.setRequestProperty("Accept", accept); connection.setRequestProperty("X-Go-Community-Context", community); String body = ""; if (params != null) { OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); body = params.toString(); out.write(body); logger.debug("Body:" + body); out.close(); } responseCode = connection.getResponseCode(); } catch (Exception e) { logger.error("Unhandled connection error:", e); throw new ValueErrorException(); } logger.info("ConnectionURL: " + connection.getURL()); if (responseCode == 403 || responseCode == 400) { logger.error("Access is denied. Invalid credentials."); throw new InvalidCredentialsException(); } if (responseCode == 404) { logger.error("URL not found."); throw new InvalidUrlException(); } if (responseCode == 500) { logger.error("Internal Server Error."); throw new ValueErrorException(); } if (responseCode != 200) { logger.info("Response code is: " + responseCode); } try { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String decodedString = in.readLine(); json = new JSONObject(decodedString); } catch (JSONException e) { logger.error("JSON Error", e); throw new ValueErrorException(); } catch (IOException e) { logger.error("IO Error", e); throw new ValueErrorException(); } return json; }
From source file:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java
/** * Write REST request to {@link HttpsURLConnection}. * //from ww w .j a v a 2 s. co m * @param endPoint String End point URL. * @param httpsMethod String HTTP method type (POST, PUT) * @param headersMap Map<String, String> Headers need to send to the end point. * @param fileName String File name of the attachment to set as binary content. * @return {@link HttpsURLConnection} object. * @throws IOException */ private HttpsURLConnection writeRequestHTTPS(String endPoint, String httpMethod, byte responseType, Map<String, String> headersMap, String fileName, boolean isBinaryContent) throws IOException { OutputStream output = null; URL url = new URL(endPoint); HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection(); // Disable automatic redirects httpsConnection.setInstanceFollowRedirects(false); httpsConnection.setRequestMethod(httpMethod); //Create byte array to send binary attachment FileInputStream fileInputStream = null; File file = new File(pathToResourcesDirectory, fileName); byte[] byteArray = new byte[(int) file.length()]; fileInputStream = new FileInputStream(file); fileInputStream.read(byteArray); fileInputStream.close(); for (String key : headersMap.keySet()) { httpsConnection.setRequestProperty(key, headersMap.get(key)); } if (httpMethod.equalsIgnoreCase("POST") || httpMethod.equalsIgnoreCase("PUT")) { httpsConnection.setDoOutput(true); try { output = httpsConnection.getOutputStream(); output.write(byteArray); } finally { if (output != null) { try { output.close(); } catch (IOException logOrIgnore) { log.error("Error while closing the connection"); } } } } return httpsConnection; }
From source file:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java
/** * Write REST request to {@link HttpsURLConnection}. * //from w w w. ja v a2s . c om * @param endPoint String End point URL. * @param httpMethod String HTTP method type (GET, POST, PUT etc.) * @param headersMap Map<String, String> Headers need to send to the end point. * @param requestFileName String File name of the file which contains request body data. * @param parametersMap Map<String, String> Additional parameters which is not predefined in the * properties file. * @return {@link HttpsURLConnection} object. * @throws IOException @ */ private HttpsURLConnection writeRequestHTTPS(String endPoint, String httpMethod, byte responseType, Map<String, String> headersMap, String requestFileName, Map<String, String> parametersMap, boolean isIgnoreHostVerification) throws IOException { String requestData = ""; if (requestFileName != null && !requestFileName.isEmpty()) { requestData = loadRequestFromFile(requestFileName, parametersMap); } else if (responseType == RestResponse.JSON_TYPE) { requestData = "{}"; } OutputStream output = null; URL url = new URL(endPoint); HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection(); // Disable automatic redirects httpsConnection.setInstanceFollowRedirects(false); httpsConnection.setRequestMethod(httpMethod); if (isIgnoreHostVerification) { httpsConnection.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); } for (String key : headersMap.keySet()) { httpsConnection.setRequestProperty(key, headersMap.get(key)); } if (httpMethod.equalsIgnoreCase("POST") || httpMethod.equalsIgnoreCase("PUT")) { httpsConnection.setDoOutput(true); try { output = httpsConnection.getOutputStream(); output.write(requestData.getBytes(Charset.defaultCharset())); } finally { if (output != null) { try { output.close(); } catch (IOException logOrIgnore) { log.error("Error while closing the connection"); } } } } return httpsConnection; }
From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java
public HttpsURLConnection makeRequest(String verb, String url, @Nullable String postData, boolean json, boolean autoredirect, @Nullable Map<String, String> customHeaders) throws IOException, URISyntaxException { String currentUrl = url;/* w ww . j a v a 2 s . c om*/ for (int i = 0; i < 30; i++) // loop for handling redirect, using automatic redirect is not possible, because // all response headers must be catched { int code; HttpsURLConnection connection = null; try { logger.debug("Make request to {}", url); connection = (HttpsURLConnection) new URL(currentUrl).openConnection(); connection.setRequestMethod(verb); connection.setRequestProperty("Accept-Language", "en-US"); if (customHeaders == null || !customHeaders.containsKey("User-Agent")) { connection.setRequestProperty("User-Agent", userAgent); } connection.setRequestProperty("Accept-Encoding", "gzip"); connection.setRequestProperty("DNT", "1"); connection.setRequestProperty("Upgrade-Insecure-Requests", "1"); if (customHeaders != null) { for (String key : customHeaders.keySet()) { String value = customHeaders.get(key); if (StringUtils.isNotEmpty(value)) { connection.setRequestProperty(key, value); } } } connection.setInstanceFollowRedirects(false); // add cookies URI uri = connection.getURL().toURI(); if (customHeaders == null || !customHeaders.containsKey("Cookie")) { StringBuilder cookieHeaderBuilder = new StringBuilder(); for (HttpCookie cookie : cookieManager.getCookieStore().get(uri)) { if (cookieHeaderBuilder.length() > 0) { cookieHeaderBuilder.append(";"); } cookieHeaderBuilder.append(cookie.getName()); cookieHeaderBuilder.append("="); cookieHeaderBuilder.append(cookie.getValue()); if (cookie.getName().equals("csrf")) { connection.setRequestProperty("csrf", cookie.getValue()); } } if (cookieHeaderBuilder.length() > 0) { String cookies = cookieHeaderBuilder.toString(); connection.setRequestProperty("Cookie", cookies); } } if (postData != null) { logger.debug("{}: {}", verb, postData); // post data byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8); int postDataLength = postDataBytes.length; connection.setFixedLengthStreamingMode(postDataLength); if (json) { connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); } else { connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); if (verb == "POST") { connection.setRequestProperty("Expect", "100-continue"); } connection.setDoOutput(true); OutputStream outputStream = connection.getOutputStream(); outputStream.write(postDataBytes); outputStream.close(); } // handle result code = connection.getResponseCode(); String location = null; // handle response headers Map<String, List<String>> headerFields = connection.getHeaderFields(); for (Map.Entry<String, List<String>> header : headerFields.entrySet()) { String key = header.getKey(); if (StringUtils.isNotEmpty(key)) { if (key.equalsIgnoreCase("Set-Cookie")) { // store cookie for (String cookieHeader : header.getValue()) { if (StringUtils.isNotEmpty(cookieHeader)) { List<HttpCookie> cookies = HttpCookie.parse(cookieHeader); for (HttpCookie cookie : cookies) { cookieManager.getCookieStore().add(uri, cookie); } } } } if (key.equalsIgnoreCase("Location")) { // get redirect location location = header.getValue().get(0); if (StringUtils.isNotEmpty(location)) { location = uri.resolve(location).toString(); // check for https if (location.toLowerCase().startsWith("http://")) { // always use https location = "https://" + location.substring(7); logger.debug("Redirect corrected to {}", location); } } } } } if (code == 200) { logger.debug("Call to {} succeeded", url); return connection; } if (code == 302 && location != null) { logger.debug("Redirected to {}", location); currentUrl = location; if (autoredirect) { continue; } return connection; } } catch (IOException e) { if (connection != null) { connection.disconnect(); } logger.warn("Request to url '{}' fails with unkown error", url, e); throw e; } catch (Exception e) { if (connection != null) { connection.disconnect(); } throw e; } if (code != 200) { throw new HttpException(code, verb + " url '" + url + "' failed: " + connection.getResponseMessage()); } } throw new ConnectionException("Too many redirects"); }