List of usage examples for javax.net.ssl HttpsURLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:com.yahoo.athenz.example.http.tls.client.HttpTLSClient.java
public static void main(String[] args) { // parse our command line to retrieve required input CommandLine cmd = parseCommandLine(args); final String url = cmd.getOptionValue("url"); final String keyPath = cmd.getOptionValue("key"); final String certPath = cmd.getOptionValue("cert"); final String trustStorePath = cmd.getOptionValue("trustStorePath"); final String trustStorePassword = cmd.getOptionValue("trustStorePassword"); // we are going to setup our service private key and // certificate into a ssl context that we can use with // our http client try {// w ww . j a v a 2s . c o m KeyRefresher keyRefresher = Utils.generateKeyRefresher(trustStorePath, trustStorePassword, certPath, keyPath); SSLContext sslContext = Utils.buildSSLContext(keyRefresher.getKeyManagerProxy(), keyRefresher.getTrustManagerProxy()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection(); con.setReadTimeout(15000); con.setDoOutput(true); con.connect(); try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()))) { StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } System.out.println("Data output: " + sb.toString()); } } catch (Exception ex) { System.out.println("Exception: " + ex.getMessage()); ex.printStackTrace(); System.exit(1); } }
From source file:com.clearcenter.mobile_demo.mdRest.java
static private HttpsURLConnection CreateConnection(URL url) throws IOException { System.setProperty("http.keepAlive", "false"); HttpsURLConnection http = (HttpsURLConnection) url.openConnection(); http.setConnectTimeout(30 * 1000);/* www . j a v a 2s .c om*/ http.setReadTimeout(30 * 1000); http.setUseCaches(false); http.setDoInput(true); http.setDoOutput(true); http.setUseCaches(false); return http; }
From source file:com.ibm.mobilefirst.mobileedge.utils.RequestUtils.java
public static void executeTrainRequest(String name, String uuid, List<AccelerometerData> accelerometerData, List<GyroscopeData> gyroscopeData, RequestResult requestResult) throws IOException { URL url = new URL("https://medge.mybluemix.net/alg/train"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setReadTimeout(5000); conn.setConnectTimeout(10000);/*from w ww . jav a2s .com*/ conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoInput(true); conn.setDoOutput(true); JSONObject jsonToSend = createTrainBodyJSON(name, uuid, accelerometerData, gyroscopeData); OutputStream outputStream = conn.getOutputStream(); DataOutputStream wr = new DataOutputStream(outputStream); wr.writeBytes(jsonToSend.toString()); wr.flush(); wr.close(); outputStream.close(); String response = ""; int responseCode = conn.getResponseCode(); //Log.e("BBB2","" + responseCode); if (responseCode == HttpsURLConnection.HTTP_OK) { String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = br.readLine()) != null) { response += line; } } else { response = "{}"; } handleResponse(response, requestResult); }
From source file:com.dmsl.anyplace.utils.NetworkUtils.java
public static InputStream downloadHttps(String urlS) throws IOException, URISyntaxException { InputStream is = null;// w ww.j av a 2 s . c om URL url = new URL(encodeURL(urlS)); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); int response = conn.getResponseCode(); if (response == 200) { is = conn.getInputStream(); } return is; }
From source file:give_me_coins.dashboard.JSONHelper.java
private static JSONObject getJSONFromUrl(URL para_url) { // ProgressDialog oShowProgress = ProgressDialog.show(oAct, "Loading", "Loading", true, false); JSONObject oRetJson = null;/*from ww w .j a v a 2 s .c o m*/ try { //Log.d(TAG,para_url.toString()); BufferedInputStream oInput = null; HttpsURLConnection oConnection = (HttpsURLConnection) para_url.openConnection(); // HttpsURLConnection.setDefaultHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); oConnection.setConnectTimeout(iConnectionTimeout); oConnection.setReadTimeout(iConnectionTimeout * 2); // connection.setRequestProperty ("Authorization", sAuthorization); oConnection.connect(); oInput = new BufferedInputStream(oConnection.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(oInput)); String sReturn = reader.readLine(); //Log.d(TAG,sReturn); oRetJson = new JSONObject(sReturn); } catch (SocketTimeoutException e) { Log.d(TAG, "Timeout"); } catch (IOException e) { Log.e(TAG, e.toString()); } catch (JSONException e) { Log.e(TAG, e.toString()); } catch (Exception e) { Log.e(TAG, e.toString()); } //para_ProgressDialog.dismiss(); return oRetJson; }
From source file:au.id.micolous.frogjump.Util.java
public static void updateCheck(final Activity activity) { (new AsyncTask<Void, Void, Boolean>() { @Override// w w w.ja v a 2s .co m protected Boolean doInBackground(Void... voids) { try { String my_version = Integer.toString(getVersionCode()); URL url = new URL("https://micolous.github.io/frogjump/version.json"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.connect(); int responseCode = conn.getResponseCode(); if (responseCode == 200) { InputStream is = conn.getInputStream(); byte[] buffer = new byte[1024]; if (is.read(buffer) == 0) { Log.i(TAG, "Error reading update file, 0 bytes"); return false; } JSONObject root = (JSONObject) new JSONTokener(new String(buffer, "US-ASCII")).nextValue(); if (root.has(my_version)) { if (root.getBoolean(my_version)) { // Definitely needs update. Log.i(TAG, "New version required, explicit flag."); return true; } } else { // unlisted version, assume it is old. Log.i(TAG, "New version required, not in list."); return true; } } } catch (Exception ex) { Log.e(TAG, "Error getting update info", ex); } return false; } @Override protected void onPostExecute(Boolean needsUpdate) { if (needsUpdate) newVersionAlert(activity); } }).execute(); }
From source file:learn.encryption.ssl.SSLContext_Https.java
/** * Post??web??,?utf-8// ww w . j a v a 2 s. com * * ?UTF8 * * @param actionUrl * @param params * @param timeout * @return * @throws InvalidParameterException * @throws NetWorkException * @throws IOException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws Exception */ public static String post(String url, Map<String, String> params, int timeout) throws IOException, IllegalArgumentException, IllegalAccessException { if (url == null || url.equals("")) throw new IllegalArgumentException("url "); if (params == null) throw new IllegalArgumentException("params ?"); if (url.indexOf('?') > 0) { url = url + "&token=A04BCQULBDgEFB1BQk5cU1NRU19cQU1WWkBPCg0FAwIkCVpZWl1UVExTXFRDSFZSSVlPSkADGhw7HAoQEQMDRFhAWUJYV0hBVE4JAxQLCQlPQ1oiNig/KSsmSEBPGBsAFxkDEkBYSF1eTk1USVldU1FQSEBPFh0OMQhPXEBQSBE="; } else { url = url + "?token=A04BCQULBDgEFB1BQk5cU1NRU19cQU1WWkBPCg0FAwIkCVpZWl1UVExTXFRDSFZSSVlPSkADGhw7HAoQEQMDRFhAWUJYV0hBVE4JAxQLCQlPQ1oiNig/KSsmSEBPGBsAFxkDEkBYSF1eTk1USVldU1FQSEBPFh0OMQhPXEBQSBE="; } String sb2 = ""; String BOUNDARY = java.util.UUID.randomUUID().toString(); String PREFIX = "--", LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8"; // try { URL uri = new URL(url); HttpsURLConnection conn = (HttpsURLConnection) uri.openConnection(); // conn.setConnectTimeout(timeout); conn.setReadTimeout(timeout); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); SSLSocketFactory ssf = sslContext.getSocketFactory(); conn.setSSLSocketFactory(ssf); conn.setHostnameVerifier(HOSTNAME_VERIFIER); StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINEND); sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND); sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND); sb.append("Content-Transfer-Encoding: 8bit" + LINEND); sb.append(LINEND); sb.append(entry.getValue()); sb.append(LINEND); } DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(sb.toString().getBytes("UTF-8")); InputStream in = null; byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); outStream.flush(); int res = conn.getResponseCode(); if (res == 200) { in = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8")); String line = ""; for (line = br.readLine(); line != null; line = br.readLine()) { sb2 = sb2 + line; } } outStream.close(); conn.disconnect(); return sb2; }
From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java
public static JSONObject sendRequest(JSONObject request, String endpoint) { URL url;/* w w w. j av a 2 s. c o m*/ try { url = new URL(authServer + "/" + endpoint); } catch (MalformedURLException e) { return null; } try { HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setDoOutput(true); con.setInstanceFollowRedirects(false); con.setReadTimeout(5000); con.setConnectTimeout(5000); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); con.connect(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8)); try { request.writeJSONString(writer); writer.flush(); writer.close(); if (con.getResponseCode() != 200) { return null; } BufferedReader reader = new BufferedReader( new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); try { JSONParser parser = new JSONParser(); try { return (JSONObject) parser.parse(reader); } catch (ParseException e) { return null; } } finally { reader.close(); } } finally { writer.close(); con.disconnect(); } } catch (IOException e) { e.printStackTrace(); return null; } }
From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java
@SuppressWarnings("unchecked") public static void authServer17(String hash) throws IOException { URL url;// w w w . j a v a2s.c o m String username; String accessToken; try { if (loginDetails == null) { throw new IOException("Not logged in"); } try { username = URLEncoder.encode(getUsername(), "UTF-8"); accessToken = URLEncoder.encode(getAccessToken(), "UTF-8"); hash = URLEncoder.encode(hash, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IOException("Username/password encoding error", e); } String urlString; urlString = sessionServer17; url = new URL(urlString); } catch (MalformedURLException e) { throw new IOException("Auth server URL error", e); } HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setDoOutput(true); con.setInstanceFollowRedirects(false); con.setReadTimeout(5000); con.setConnectTimeout(5000); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); con.connect(); JSONObject obj = new JSONObject(); obj.put("accessToken", accessToken); obj.put("selectedProfile", loginDetails.get("selectedProfile")); obj.put("serverId", hash); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8)); try { obj.writeJSONString(writer); writer.flush(); writer.close(); } catch (IOException e) { if (writer != null) { writer.close(); con.disconnect(); return; } } if (con.getResponseCode() != 200) { throw new IOException("Unable to verify username, please restart proxy"); } BufferedReader reader = new BufferedReader( new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); try { String reply = reader.readLine(); if (reply != null) { throw new IOException("Auth server replied (" + reply + ")"); } } finally { reader.close(); con.disconnect(); } }
From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java
public static HttpsResponse getRequest(String Uri, String requestParameters) throws IOException { if (Uri.startsWith("https://")) { String urlStr = Uri;// w w w . ja v a 2s . c om if (requestParameters != null && requestParameters.length() > 0) { urlStr += "?" + requestParameters; } URL url = new URL(urlStr); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true); conn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); conn.setReadTimeout(30000); conn.connect(); // Get the response StringBuilder sb = new StringBuilder(); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } } catch (FileNotFoundException ignored) { } catch (IOException ignored) { } finally { if (rd != null) { rd.close(); } conn.disconnect(); } return new HttpsResponse(sb.toString(), conn.getResponseCode()); } return null; }