List of usage examples for javax.net.ssl HttpsURLConnection getURL
public URL getURL()
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 w w . ja va 2s.c o m 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"); }
From source file:org.globusonline.nexus.BaseNexusRestClient.java
/** * @param path//from ww w . j a v a2 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; }