List of usage examples for javax.net.ssl HttpsURLConnection connect
public abstract void connect() throws IOException;
From source file:com.mikhaellopez.saveinsta.activity.MainActivity.java
private boolean downloadVideo(String urlVideo, String fileName) { boolean result = false; OutputStream output = null;/*from www .j ava 2s. c om*/ InputStream input = null; try { File root = new File(Environment.getExternalStorageDirectory() + File.separator + getResources().getString(R.string.app_name) + File.separator); root.mkdirs(); File sdImageMainDirectory = new File(root, fileName); // Download Video URL url = new URL(urlVideo); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.connect(); input = urlConnection.getInputStream(); output = new FileOutputStream(sdImageMainDirectory); byte[] data = new byte[input.available()]; input.read(data); output.write(data); byte[] buffer = new byte[1024]; int len1; while ((len1 = input.read(buffer)) > 0) { output.write(buffer, 0, len1); } result = true; } catch (Exception e) { e.printStackTrace(); } finally { if (null != output) { try { output.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != input) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; }
From source file:org.whispersystems.textsecure.push.PushServiceSocket.java
private void uploadExternalFile(String method, String url, byte[] data) throws IOException { URL uploadUrl = new URL(url); HttpsURLConnection connection = (HttpsURLConnection) uploadUrl.openConnection(); connection.setDoOutput(true);//from w w w .j a v a2 s . com connection.setRequestMethod(method); connection.setRequestProperty("Content-Type", "application/octet-stream"); connection.connect(); try { OutputStream out = connection.getOutputStream(); out.write(data); out.close(); if (connection.getResponseCode() != 200) { throw new IOException( "Bad response: " + connection.getResponseCode() + " " + connection.getResponseMessage()); } } finally { connection.disconnect(); } }
From source file:org.jembi.rhea.rapidsms.GenerateORU_R01Alert.java
public String callQueryFacility(String msg) throws IOException, TransformerFactoryConfigurationError, TransformerException { // Setup connection URL url = new URL(hostname + "/ws/rest/v1/alerts"); System.out.println("full url " + url); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setDoOutput(true);//from w w w . j a v a 2s . c o m conn.setRequestMethod("POST"); conn.setDoInput(true); // This is important to get the connection to use our trusted // certificate conn.setSSLSocketFactory(sslFactory); addHTTPBasicAuthProperty(conn); // conn.setConnectTimeout(timeOut); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); log.error("body" + msg); out.write(msg); out.close(); conn.connect(); // Test response code if (conn.getResponseCode() != 200) { throw new IOException(conn.getResponseMessage()); } String result = convertInputStreamToString(conn.getInputStream()); conn.disconnect(); return result; }
From source file:com.gmt2001.TwitchAPIv2.java
private JSONObject GetData(request_type type, String url, String post, String oauth) { JSONObject j = new JSONObject(); try {/*ww w. j av a 2s. co m*/ URL u = new URL(url); HttpsURLConnection c = (HttpsURLConnection) u.openConnection(); c.addRequestProperty("Accept", header_accept); if (!clientid.isEmpty()) { c.addRequestProperty("Client-ID", clientid); } if (!oauth.isEmpty()) { c.addRequestProperty("Authorization", "OAuth " + oauth); } c.setRequestMethod(type.name()); c.setUseCaches(false); c.setDefaultUseCaches(false); c.setConnectTimeout(timeout); c.connect(); if (!post.isEmpty()) { IOUtils.write(post, c.getOutputStream()); } String content; if (c.getResponseCode() == 200) { content = IOUtils.toString(c.getInputStream(), c.getContentEncoding()); } else { content = IOUtils.toString(c.getErrorStream(), c.getContentEncoding()); } j = new JSONObject(content); j.put("_success", true); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", c.getResponseCode()); j.put("_exception", ""); j.put("_exceptionMessage", ""); } catch (MalformedURLException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", "MalformedURLException"); j.put("_exceptionMessage", ex.getMessage()); } catch (SocketTimeoutException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", "SocketTimeoutException"); j.put("_exceptionMessage", ex.getMessage()); } catch (IOException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", "IOException"); j.put("_exceptionMessage", ex.getMessage()); } catch (Exception ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", "Exception [" + ex.getClass().getName() + "]"); j.put("_exceptionMessage", ex.getMessage()); } return j; }
From source file:fr.qinder.api.APIGetter.java
protected HttpsURLConnection post(String sUrl, APIRequest request) { HttpsURLConnection urlConnection; URL url;/*from w w w . j av a2 s . co m*/ try { url = new URL(sUrl); urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); if (request.getPosts().size() != 0) { urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(request.getPosts()); OutputStream post = urlConnection.getOutputStream(); entity.writeTo(post); post.flush(); } urlConnection.connect(); } catch (IOException e) { urlConnection = null; } return urlConnection; }
From source file:tetujin.nikeapi.core.JNikeLowLevelAPI.java
/** * // w w w. j a v a 2 s. c o m * @param strURL ?URL * @return jsonStr JSON?? */ protected String sendHttpRequest(final String strURL) { String jsonStr = ""; try { URL url = new URL(strURL); /*---------make and set HTTP header-------*/ //HttpsURLConnection baseConnection = (HttpsURLConnection)url.openConnection(); HttpsURLConnection con = setHttpHeader((HttpsURLConnection) url.openConnection()); /*---------show HTTP header information-------*/ System.out.println("\n ---------http header---------- "); Map headers = con.getHeaderFields(); for (Object key : headers.keySet()) { System.out.println(key + ": " + headers.get(key)); } con.connect(); /*---------get HTTP body information---------*/ String contentType = con.getHeaderField("Content-Type"); //String charSet = "Shift-JIS";// "ISO-8859-1"; String charSet = "UTF-8";// "ISO-8859-1"; for (String elm : contentType.replace(" ", "").split(";")) { if (elm.startsWith("charset=")) { charSet = elm.substring(8); break; } } /*---------show HTTP body information----------*/ BufferedReader br; try { br = new BufferedReader(new InputStreamReader(con.getInputStream(), charSet)); } catch (Exception e_) { System.out.println(con.getResponseCode() + " " + con.getResponseMessage()); br = new BufferedReader(new InputStreamReader(con.getErrorStream(), charSet)); } System.out.println("\n ---------show HTTP body information----------"); String line = ""; while ((line = br.readLine()) != null) { jsonStr += line; } br.close(); con.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println(jsonStr); return jsonStr; }
From source file:org.openmrs.module.rheashradapter.util.GenerateORU_R01Alert.java
public String callQueryFacility(String msg, Encounter e) throws IOException, TransformerFactoryConfigurationError, TransformerException { Cohort singlePatientCohort = new Cohort(); singlePatientCohort.addMember(e.getPatient().getId()); Map<Integer, String> patientIdentifierMap = Context.getPatientSetService() .getPatientIdentifierStringsByType(singlePatientCohort, Context.getPatientService() .getPatientIdentifierTypeByName(RHEAHL7Constants.IDENTIFIER_TYPE)); // Setup connection String id = patientIdentifierMap.get(patientIdentifierMap.keySet().iterator().next()); URL url = new URL(hostname + "/ws/rest/v1/alerts"); System.out.println("full url " + url); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setDoOutput(true);/*from w ww. j a v a 2s . com*/ conn.setRequestMethod("POST"); conn.setDoInput(true); // This is important to get the connection to use our trusted // certificate conn.setSSLSocketFactory(sslFactory); addHTTPBasicAuthProperty(conn); // conn.setConnectTimeout(timeOut); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); log.error("body" + msg); out.write(msg); out.close(); conn.connect(); String headerValue = conn.getHeaderField("http.status"); // Test response code if (conn.getResponseCode() != 200) { throw new IOException(conn.getResponseMessage()); } String result = convertInputStreamToString(conn.getInputStream()); conn.disconnect(); return result; }
From source file:online.privacy.PrivacyOnlineApiRequest.java
private JSONObject makeAPIRequest(String method, String endPoint, String jsonPayload) throws IOException, JSONException { InputStream inputStream = null; OutputStream outputStream = null; String apiUrl = "https://api.privacy.online"; String apiKey = this.context.getString(R.string.privacy_online_api_key); String keyString = "?key=" + apiKey; int payloadSize = jsonPayload.length(); try {/* ww w. jav a 2s . co m*/ URL url = new URL(apiUrl + endPoint + keyString); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); // Sec 5 second connect/read timeouts connection.setReadTimeout(5000); connection.setConnectTimeout(5000); connection.setRequestMethod(method); connection.setRequestProperty("Content-Type", "application/json"); if (payloadSize > 0) { connection.setDoInput(true); connection.setDoOutput(true); connection.setFixedLengthStreamingMode(payloadSize); } // Initiate the connection connection.connect(); // Write the payload if there is one. if (payloadSize > 0) { outputStream = connection.getOutputStream(); outputStream.write(jsonPayload.getBytes("UTF-8")); } // Get the response code ... int responseCode = connection.getResponseCode(); Log.e(LOG_TAG, "Response code: " + responseCode); switch (responseCode) { case HttpsURLConnection.HTTP_OK: inputStream = connection.getInputStream(); break; case HttpsURLConnection.HTTP_FORBIDDEN: inputStream = connection.getErrorStream(); break; case HttpURLConnection.HTTP_NOT_FOUND: inputStream = connection.getErrorStream(); break; case HttpsURLConnection.HTTP_UNAUTHORIZED: inputStream = connection.getErrorStream(); break; default: inputStream = connection.getInputStream(); break; } String responseContent = "{}"; // Default to an empty object. if (inputStream != null) { responseContent = readInputStream(inputStream, connection.getContentLength()); } JSONObject responseObject = new JSONObject(responseContent); responseObject.put("code", responseCode); return responseObject; } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } }
From source file:com.microsoft.speech.tts.Authentication.java
private void HttpPost(String AccessTokenUri, String apiKey) { InputStream inSt = null;//from w ww .j a v a 2s. c o m HttpsURLConnection webRequest = null; this.accessToken = null; //Prepare OAuth request try { URL url = new URL(AccessTokenUri); webRequest = (HttpsURLConnection) url.openConnection(); webRequest.setDoInput(true); webRequest.setDoOutput(true); webRequest.setConnectTimeout(5000); webRequest.setReadTimeout(5000); webRequest.setRequestProperty("Ocp-Apim-Subscription-Key", apiKey); webRequest.setRequestMethod("POST"); String request = ""; byte[] bytes = request.getBytes(); webRequest.setRequestProperty("content-length", String.valueOf(bytes.length)); webRequest.connect(); DataOutputStream dop = new DataOutputStream(webRequest.getOutputStream()); dop.write(bytes); dop.flush(); dop.close(); inSt = webRequest.getInputStream(); InputStreamReader in = new InputStreamReader(inSt); BufferedReader bufferedReader = new BufferedReader(in); StringBuffer strBuffer = new StringBuffer(); String line = null; while ((line = bufferedReader.readLine()) != null) { strBuffer.append(line); } bufferedReader.close(); in.close(); inSt.close(); webRequest.disconnect(); this.accessToken = strBuffer.toString(); } catch (Exception e) { Log.e(LOG_TAG, "Exception error", e); } }
From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java
@Override public String execute(String request, int connectTimeout, int readTimeout) { // NOTE: We will only show exceptions in the debug level, because they will be handled in the checkConnection() // method and this changes the bridge state. If a command was send it fails than and a sensorJob will be // execute the next time, by TimeOutExceptions. By other exceptions the checkConnection() method handles it in // max 1 second. String response = null;// www .j a v a 2s . co m HttpsURLConnection connection = null; try { String correctedRequest = checkSessionToken(request); connection = getConnection(correctedRequest, connectTimeout, readTimeout); if (connection != null) { connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_FORBIDDEN) { if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) { response = IOUtils.toString(connection.getErrorStream()); } else { response = IOUtils.toString(connection.getInputStream()); } if (response != null) { if (!response.contains("Authentication failed")) { if (loginCounter > 0) { connectionManager.checkConnection(responseCode); } loginCounter = 0; } else { connectionManager.checkConnection(ConnectionManager.AUTHENTIFICATION_PROBLEM); loginCounter++; } } } connection.disconnect(); if (response == null && connectionManager != null && loginCounter <= MAY_A_NEW_SESSION_TOKEN_IS_NEEDED) { if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) { execute(addSessionToken(correctedRequest, connectionManager.getNewSessionToken()), connectTimeout, readTimeout); loginCounter++; } else { connectionManager.checkConnection(responseCode); loginCounter++; return null; } } return response; } } catch (SocketTimeoutException e) { informConnectionManager(ConnectionManager.SOCKET_TIMEOUT_EXCEPTION); } catch (java.net.ConnectException e) { informConnectionManager(ConnectionManager.CONNECTION_EXCEPTION); } catch (MalformedURLException e) { informConnectionManager(ConnectionManager.MALFORMED_URL_EXCEPTION); } catch (java.net.UnknownHostException e) { informConnectionManager(ConnectionManager.UNKNOWN_HOST_EXCEPTION); } catch (IOException e) { logger.error("An IOException occurred: ", e); if (connectionManager != null) { informConnectionManager(ConnectionManager.GENERAL_EXCEPTION); } } finally { if (connection != null) { connection.disconnect(); } } return null; }