List of usage examples for javax.net.ssl HttpsURLConnection disconnect
public abstract void disconnect();
From source file:iracing.webapi.IracingWebApi.java
/** * /*from w w w.j a va 2 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:io.github.protino.codewatch.remote.FetchLeaderBoardData.java
private List<String> fetchLeaderBoardJson() { HttpsURLConnection urlConnection = null; BufferedReader reader = null; List<String> jsonDataList = new ArrayList<>(); try {/*from w ww . j a v a 2s.c o m*/ final String LEADER_PATH = "leaders"; final String API_SUFFIX = "api/v1"; final String API_KEY = "api_key"; final String PAGE = "page"; Uri.Builder builder; String jsonStr; int totalPages = -1; int page = 1; do { builder = Uri.parse(Constants.WAKATIME_BASE_URL).buildUpon(); builder.appendPath(API_SUFFIX).appendPath(LEADER_PATH) .appendQueryParameter(API_KEY, BuildConfig.API_KEY) .appendQueryParameter(PAGE, String.valueOf(page)).build(); URL url = new URL(builder.toString()); // Create the request to Wakatime.com, and open the connection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a string InputStream inputStream = urlConnection.getInputStream(); StringBuilder buffer = new StringBuilder(); if (inputStream == null) { return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { buffer.append(line); } if (buffer.length() == 0) { return null; } jsonStr = buffer.toString(); jsonDataList.add(jsonStr); //parse totalpages if (totalPages == -1) { totalPages = new JSONObject(jsonStr).getInt("total_pages"); } page++; } while (totalPages != page); } catch (IOException e) { Timber.e(e, "IO Error"); } catch (JSONException e) { Timber.e(e, "JSON error"); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); Timber.e(e, "Error closing stream"); } } } return jsonDataList; }
From source file:io.github.protino.codewatch.remote.FetchLeaderBoardData.java
public int fetchUserRank() { AccessToken accessToken = CacheUtils.getAccessToken(context); if (accessToken == null) { return -1; }/* www . ja v a2 s. c om*/ HttpsURLConnection urlConnection = null; BufferedReader reader = null; String jsonStr; try { final String LEADER_PATH = "leaders"; final String API_SUFFIX = "api/v1"; final String CLIENT_SECRET = "secret"; final String APP_SECRET = "app_secret"; final String ACCESS_TOKEN = "token"; Uri.Builder builder; builder = Uri.parse(Constants.WAKATIME_BASE_URL).buildUpon(); builder.appendPath(API_SUFFIX).appendPath(LEADER_PATH) .appendQueryParameter(APP_SECRET, BuildConfig.CLIENT_ID) .appendQueryParameter(CLIENT_SECRET, BuildConfig.CLIENT_SECRET) .appendQueryParameter(ACCESS_TOKEN, accessToken.getAccessToken()).build(); URL url = new URL(builder.toString()); // Create the request to Wakatime.com, and open the connection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a string InputStream inputStream = urlConnection.getInputStream(); StringBuilder buffer = new StringBuilder(); if (inputStream == null) { return -1; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { buffer.append(line); } if (buffer.length() == 0) { return -1; } jsonStr = buffer.toString(); JSONObject currentUser = new JSONObject(jsonStr).getJSONObject("current_user"); if (currentUser == null) { return -1; } else { //if is a new user, it'll result throw JSONException, because rank=null return currentUser.getInt("rank"); } } catch (IOException e) { Timber.e(e, "IO Error"); return -1; } catch (JSONException e) { Timber.e(e, "JSON error"); return -1; } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); Timber.e(e, "Error closing stream"); } } } }
From source file:br.com.intelidev.dao.DadosDao.java
public List<Dados> get_stream_data(String stream_api, String user, String pass) { HttpsURLConnection conn = null; List<Dados> list_return = new ArrayList<>(); int i;//from w ww . j av a 2 s . c o m try { // Create url to the Device Cloud server for a given web service request //00000000-00000000-00409DFF-FF6064F8/xbee.analog/[00:13:A2:00:40:E6:5A:88]!/AD1 ObjectMapper mapper = new ObjectMapper(); URL url = new URL("https://devicecloud.digi.com/ws/v1/streams/history/" + stream_api); //URL url = new URL("https://devicecloud.digi.com/ws/v1/streams/history/00000000-00000000-00409DFF-FF6064F8/xbee.analog/[00:13:A2:00:40:E6:5A:88]!/AD1"); conn = (HttpsURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("GET"); // Build authentication string String userpassword = user + ":" + pass; System.out.println(userpassword); // can change this to use a different base64 encoder String encodedAuthorization = Base64.encodeBase64String(userpassword.getBytes()).trim(); // set request headers conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization); // Get input stream from response and convert to String InputStream is = conn.getInputStream(); Scanner isScanner = new Scanner(is); StringBuffer buf = new StringBuffer(); while (isScanner.hasNextLine()) { buf.append(isScanner.nextLine() + "\n"); } String responseContent = buf.toString(); // add line returns between tags to make it a bit more readable responseContent = responseContent.replaceAll("><", ">\n<"); // Output response to standard out System.out.println(responseContent); // Convert JSON string to Object StreamDados stream = mapper.readValue(responseContent, StreamDados.class); //System.out.println(stream.getList()); System.out.println(stream.getList().size()); for (i = 0; i < stream.getList().size(); i++) { list_return.add(stream.getList().get(i)); //System.out.println("ts: "+ stream.getList().get(i).getTimestamp() + "Value: " + stream.getList().get(i).getValue()); } } catch (Exception e) { // Print any exceptions that occur System.out.println("br.com.intelidev.dao.DadosDao.get_stream_data() e" + e); } finally { if (conn != null) conn.disconnect(); } return list_return; }
From source file:org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest.java
public RestResponse httpsSendGet(String url, Map<String, String> headers) throws IOException { RestResponse restResponse = new RestResponse(); URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); // add request header if (headers != null) { for (Entry<String, String> header : headers.entrySet()) { String key = header.getKey(); String value = header.getValue(); con.setRequestProperty(key, value); }//from w w w . ja v a 2 s.co m } int responseCode = con.getResponseCode(); logger.debug("Send GET http request, url: {}", url); logger.debug("Response Code: {}", responseCode); StringBuffer response = new StringBuffer(); try { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } catch (Exception e) { logger.debug("response body is null"); } String result; try { result = IOUtils.toString(con.getErrorStream()); response.append(result); } catch (Exception e2) { // result = null; } logger.debug("Response body: {}", response); // print result restResponse.setErrorCode(responseCode); if (response != null) { restResponse.setResponse(response.toString()); } restResponse.setErrorCode(responseCode); // restResponse.setResponse(result); Map<String, List<String>> headerFields = con.getHeaderFields(); restResponse.setHeaderFields(headerFields); String responseMessage = con.getResponseMessage(); restResponse.setResponseMessage(responseMessage); con.disconnect(); return restResponse; }
From source file:org.wso2.carbon.identity.authenticator.wikid.WiKIDAuthenticator.java
/** * Send REST call//w w w . j a v a 2s . co m */ private String sendRESTCall(String url, String urlParameters, String formParameters, String httpMethod) { String line; StringBuilder responseString = new StringBuilder(); HttpsURLConnection connection = null; try { setHttpsClientCert( "/media/sf_SharedFoldersToVBox/is-connectors/wikid/wikid-authenticator/org.wso2.carbon.identity.authenticator/src/main/resources/localhostWiKID", "shakila"); SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); URL wikidEP = new URL(url + urlParameters); connection = (HttpsURLConnection) wikidEP.openConnection(); connection.setSSLSocketFactory(sslsocketfactory); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod(httpMethod); connection.setRequestProperty(WiKIDAuthenticatorConstants.HTTP_CONTENT_TYPE, WiKIDAuthenticatorConstants.HTTP_CONTENT_TYPE_XWFUE); if (httpMethod.toUpperCase().equals(WiKIDAuthenticatorConstants.HTTP_POST)) { OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), WiKIDAuthenticatorConstants.CHARSET); writer.write(formParameters); writer.close(); } if (connection.getResponseCode() == 200) { BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = br.readLine()) != null) { responseString.append(line); } br.close(); } else { return WiKIDAuthenticatorConstants.FAILED + WiKIDAuthenticatorConstants.REQUEST_FAILED; } } catch (ProtocolException e) { if (log.isDebugEnabled()) { log.debug(WiKIDAuthenticatorConstants.FAILED + e.getMessage()); } return WiKIDAuthenticatorConstants.FAILED + e.getMessage(); } catch (MalformedURLException e) { if (log.isDebugEnabled()) { log.debug(WiKIDAuthenticatorConstants.FAILED + e.getMessage()); } return WiKIDAuthenticatorConstants.FAILED + e.getMessage(); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug(WiKIDAuthenticatorConstants.FAILED + e.getMessage()); } return WiKIDAuthenticatorConstants.FAILED + e.getMessage(); } finally { connection.disconnect(); } return responseString.toString(); }
From source file:com.dagobert_engine.core.service.MtGoxApiAdapter.java
/** * Queries the mtgox api with params/*from ww w. ja va2 s. c o m*/ * * @param url * @return */ public String query(String path, HashMap<String, String> args) { final String publicKey = mtGoxConfig.getMtGoxPublicKey(); final String privateKey = mtGoxConfig.getMtGoxPrivateKey(); if (publicKey == null || privateKey == null || "".equals(publicKey) || "".equals(privateKey)) { throw new ApiKeysNotSetException( "Either public or private key of MtGox are not set. Please set them up in src/main/resources/META-INF/seam-beans.xml"); } // Create nonce final String nonce = String.valueOf(System.currentTimeMillis()) + "000"; HttpsURLConnection connection = null; String answer = null; try { // add nonce and build arg list args.put(ARG_KEY_NONCE, nonce); String post_data = buildQueryString(args); String hash_data = path + "\0" + post_data; // Should be correct // args signature with apache cryptografic tools String signature = signRequest(mtGoxConfig.getMtGoxPrivateKey(), hash_data); // build URL URL queryUrl = new URL(Constants.API_BASE_URL + path); // create and setup a HTTP connection connection = (HttpsURLConnection) queryUrl.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty(REQ_PROP_USER_AGENT, com.dagobert_engine.core.util.Constants.APP_NAME); connection.setRequestProperty(REQ_PROP_REST_KEY, mtGoxConfig.getMtGoxPublicKey()); connection.setRequestProperty(REQ_PROP_REST_SIGN, signature.replaceAll("\n", "")); connection.setDoOutput(true); connection.setDoInput(true); // Read the response DataOutputStream os = new DataOutputStream(connection.getOutputStream()); os.writeBytes(post_data); os.close(); BufferedReader br = null; // Any error? int code = connection.getResponseCode(); if (code >= 400) { // get error stream br = new BufferedReader(new InputStreamReader((connection.getErrorStream()))); answer = toString(br); logger.severe("HTTP Error on queryin " + path + ": " + code + ", answer: " + answer); throw new MtGoxConnectionError(code, answer); } else { // get normal stream br = new BufferedReader(new InputStreamReader((connection.getInputStream()))); answer = toString(br); } } catch (UnknownHostException exc) { throw new MtGoxConnectionError("Could not connect to MtGox. Please check your internet connection. (" + exc.getClass().getName() + ")"); } catch (IllegalStateException ex) { throw new MtGoxConnectionError(ex); } catch (IOException ex) { throw new MtGoxConnectionError(ex); } finally { if (connection != null) connection.disconnect(); connection = null; } return answer; }
From source file:org.wso2.carbon.identity.authenticator.mepin.MepinTransactions.java
private String postRequest(String url, String query, String username, String password) throws IOException { String authStr = username + ":" + password; String encoding = new String(Base64.encodeBase64(authStr.getBytes())); String responseString = ""; HttpsURLConnection connection = null; BufferedReader br;// w w w.j ava 2 s . c om StringBuilder sb; String line; try { connection = (HttpsURLConnection) new URL(url).openConnection(); connection.setDoOutput(true); connection.setRequestProperty(MepinConstants.HTTP_ACCEPT_CHARSET, MepinConstants.CHARSET); connection.setRequestProperty(MepinConstants.HTTP_CONTENT_TYPE, MepinConstants.HTTP_POST_CONTENT_TYPE); connection.setRequestProperty(MepinConstants.HTTP_AUTHORIZATION, MepinConstants.HTTP_AUTHORIZATION_BASIC + encoding); OutputStream output = connection.getOutputStream(); output.write(query.getBytes(MepinConstants.CHARSET)); int status = connection.getResponseCode(); if (log.isDebugEnabled()) { log.debug("MePIN Response Code :" + status); } switch (status) { case 200: br = new BufferedReader(new InputStreamReader(connection.getInputStream())); sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); responseString = sb.toString(); break; case 201: case 400: case 403: case 404: case 500: br = new BufferedReader(new InputStreamReader(connection.getInputStream())); sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); responseString = sb.toString(); if (log.isDebugEnabled()) { log.debug("MePIN Response :" + responseString); } return MepinConstants.FAILED; } } catch (IOException e) { if (connection.getErrorStream() != null) { br = new BufferedReader(new InputStreamReader(connection.getErrorStream())); sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); responseString = sb.toString(); if (log.isDebugEnabled()) { log.debug("MePIN Response :" + responseString); } return MepinConstants.FAILED; } } finally { connection.disconnect(); } if (log.isDebugEnabled()) { log.debug("MePIN Response :" + responseString); } return responseString; }
From source file:de.thingweb.client.security.Security4NicePlugfest.java
public Registration requestRegistrationAS() throws IOException { String clientName = "opPostmanTestRS"; // CLIENT_NAME_PREFIX + // System.currentTimeMillis(); String clientCredentials = "client_credentials"; String requestBodyRegistration = "{\"client_name\": \"" + clientName + "\",\"grant_types\": [\"" + clientCredentials + "\"], \"id_token_signed_response_alg\":\"" + "HS256" + "\"}"; // Registration URL urlRegistration = new URL(HTTPS_PREFIX + HOST + REQUEST_REGISTRATION_AS); HttpsURLConnection httpConRegistration = (HttpsURLConnection) urlRegistration.openConnection(); httpConRegistration.setDoOutput(true); httpConRegistration.setRequestProperty("Host", REQUEST_HEADER_HOST); httpConRegistration.setRequestProperty("Content-Type", "application/json"); httpConRegistration.setRequestProperty("Accept", "application/json"); httpConRegistration.setRequestMethod("POST"); OutputStream outRegistration = httpConRegistration.getOutputStream(); outRegistration.write(requestBodyRegistration.getBytes()); outRegistration.close();//w w w.j a v a 2 s . co m int responseCodeRegistration = httpConRegistration.getResponseCode(); log.info("responseCode Registration for " + urlRegistration + ": " + responseCodeRegistration); if (responseCodeRegistration == 201) { // everything ok InputStream isR = httpConRegistration.getInputStream(); byte[] bisR = getBytesFromInputStream(isR); String jsonResponseRegistration = new String(bisR); log.info(jsonResponseRegistration); // extract the value of client_id (this value is called <c_id>in // the following) and the value of client_secret (called // <c_secret> in the following) from the JSON response ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser jp = factory.createParser(bisR); JsonNode actualObj = mapper.readTree(jp); JsonNode c_id = actualObj.get("client_id"); JsonNode c_secret = actualObj.get("client_secret"); if (c_id == null || c_id.getNodeType() != JsonNodeType.STRING || c_secret == null || c_secret.getNodeType() != JsonNodeType.STRING) { log.error("client_id: " + c_id); log.error("client_secret: " + c_secret); } else { // ok so far // Store <c_id> and <c_secret> for use during the token // acquisition log.info("client_id: " + c_id); log.info("client_secret: " + c_secret); return new Registration(c_id.textValue(), c_secret.textValue()); } } else { // error InputStream error = httpConRegistration.getErrorStream(); byte[] berror = getBytesFromInputStream(error); log.error(new String(berror)); } httpConRegistration.disconnect(); return null; }
From source file:de.thingweb.client.security.Security4NicePlugfest.java
public Registration requestRegistrationAM() throws IOException { Registration registration = null;/*w ww .j av a 2 s. c o m*/ String clientName = CLIENT_NAME_PREFIX + System.currentTimeMillis(); String clientCredentials = "client_credentials"; String requestBodyRegistration = "{\"client_name\": \"" + clientName + "\",\"grant_types\": [\"" + clientCredentials + "\"]}"; // Registration URL urlRegistration = new URL(HTTPS_PREFIX + HOST + REQUEST_REGISTRATION_AM); HttpsURLConnection httpConRegistration = (HttpsURLConnection) urlRegistration.openConnection(); httpConRegistration.setDoOutput(true); httpConRegistration.setRequestProperty("Host", REQUEST_HEADER_HOST); httpConRegistration.setRequestProperty("Content-Type", "application/json"); httpConRegistration.setRequestProperty("Accept", "application/json"); httpConRegistration.setRequestMethod("POST"); OutputStream outRegistration = httpConRegistration.getOutputStream(); outRegistration.write(requestBodyRegistration.getBytes()); outRegistration.close(); int responseCodeRegistration = httpConRegistration.getResponseCode(); log.info("responseCode Registration for " + urlRegistration + ": " + responseCodeRegistration); if (responseCodeRegistration == 201) { // everything ok InputStream isR = httpConRegistration.getInputStream(); byte[] bisR = getBytesFromInputStream(isR); String jsonResponseRegistration = new String(bisR); log.info(jsonResponseRegistration); // extract the value of client_id (this value is called <c_id>in // the following) and the value of client_secret (called // <c_secret> in the following) from the JSON response ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser jp = factory.createParser(bisR); JsonNode actualObj = mapper.readTree(jp); JsonNode c_id = actualObj.get("client_id"); JsonNode c_secret = actualObj.get("client_secret"); if (c_id == null || c_id.getNodeType() != JsonNodeType.STRING || c_secret == null || c_secret.getNodeType() != JsonNodeType.STRING) { log.error("client_id: " + c_id); log.error("client_secret: " + c_secret); } else { // ok so far // Store <c_id> and <c_secret> for use during the token // acquisition log.info("client_id: " + c_id); log.info("client_secret: " + c_secret); registration = new Registration(c_id.textValue(), c_secret.textValue()); } } else { // error InputStream error = httpConRegistration.getErrorStream(); byte[] berror = getBytesFromInputStream(error); log.error(new String(berror)); } httpConRegistration.disconnect(); return registration; }