List of usage examples for java.net HttpURLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:com.onesignal.OneSignalRestClient.java
private static void makeRequest(String url, String method, JSONObject jsonBody, ResponseHandler responseHandler) { HttpURLConnection con = null; int httpResponse = -1; String json = null;//from w ww. j av a2s. co m try { con = (HttpURLConnection) new URL(BASE_URL + url).openConnection(); con.setUseCaches(false); con.setDoOutput(true); con.setConnectTimeout(TIMEOUT); con.setReadTimeout(TIMEOUT); if (jsonBody != null) con.setDoInput(true); con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); con.setRequestMethod(method); if (jsonBody != null) { String strJsonBody = jsonBody.toString(); OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " SEND JSON: " + strJsonBody); byte[] sendBytes = strJsonBody.getBytes("UTF-8"); con.setFixedLengthStreamingMode(sendBytes.length); OutputStream outputStream = con.getOutputStream(); outputStream.write(sendBytes); } httpResponse = con.getResponseCode(); InputStream inputStream; Scanner scanner; if (httpResponse == HttpURLConnection.HTTP_OK) { inputStream = con.getInputStream(); scanner = new Scanner(inputStream, "UTF-8"); json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : ""; scanner.close(); OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " RECEIVED JSON: " + json); if (responseHandler != null) responseHandler.onSuccess(json); } else { inputStream = con.getErrorStream(); if (inputStream == null) inputStream = con.getInputStream(); if (inputStream != null) { scanner = new Scanner(inputStream, "UTF-8"); json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : ""; scanner.close(); OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " RECEIVED JSON: " + json); } else OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " HTTP Code: " + httpResponse + " No response body!"); if (responseHandler != null) responseHandler.onFailure(httpResponse, json, null); } } catch (Throwable t) { if (t instanceof java.net.ConnectException || t instanceof java.net.UnknownHostException) OneSignal.Log(OneSignal.LOG_LEVEL.INFO, "Could not send last request, device is offline. Throwable: " + t.getClass().getName()); else OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " Error thrown from network stack. ", t); if (responseHandler != null) responseHandler.onFailure(httpResponse, null, t); } finally { if (con != null) con.disconnect(); } }
From source file:com.gmt2001.HttpRequest.java
public static HttpResponse getData(RequestType type, String url, String post, HashMap<String, String> headers) { Thread.setDefaultUncaughtExceptionHandler(com.gmt2001.UncaughtExceptionHandler.instance()); HttpResponse r = new HttpResponse(); r.type = type;/* w w w .ja v a 2s . com*/ r.url = url; r.post = post; r.headers = headers; try { URL u = new URL(url); HttpURLConnection h = (HttpURLConnection) u.openConnection(); for (Entry<String, String> e : headers.entrySet()) { h.addRequestProperty(e.getKey(), e.getValue()); } h.setRequestMethod(type.name()); h.setUseCaches(false); h.setDefaultUseCaches(false); h.setConnectTimeout(timeout); h.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015"); if (!post.isEmpty()) { h.setDoOutput(true); } h.connect(); if (!post.isEmpty()) { BufferedOutputStream stream = new BufferedOutputStream(h.getOutputStream()); stream.write(post.getBytes()); stream.flush(); stream.close(); } if (h.getResponseCode() < 400) { r.content = IOUtils.toString(new BufferedInputStream(h.getInputStream()), h.getContentEncoding()); r.httpCode = h.getResponseCode(); r.success = true; } else { r.content = IOUtils.toString(new BufferedInputStream(h.getErrorStream()), h.getContentEncoding()); r.httpCode = h.getResponseCode(); r.success = false; } } catch (IOException ex) { r.success = false; r.httpCode = 0; r.exception = ex.getMessage(); com.gmt2001.Console.err.printStackTrace(ex); } return r; }
From source file:com.magnet.tools.tests.MagnetToolStepDefs.java
@Then("The server at \"([^\"]*)\" is down$") public static void _the_server_at_is_down(String endpointUrl) { try {//w w w . ja v a 2 s . com HttpURLConnection connection = (HttpURLConnection) new URL(endpointUrl).openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setRequestMethod("GET"); connection.getResponseCode(); Assert.fail("the endpoint " + endpointUrl + " should not have been available"); } catch (MalformedURLException e) { throw new AssertionError(e); } catch (IOException e) { // this is what we are hoping for.. } }
From source file:io.webfolder.cdp.ChromiumDownloader.java
public static ChromiumVersion getLatestVersion() { String url = DOWNLOAD_HOST;/*from ww w .j ava2 s . c om*/ if (WINDOWS) { url += "/Win_x64/LAST_CHANGE"; } else if (LINUX) { url += "/Linux_x64/LAST_CHANGE"; } else if (MAC) { url += "/Mac/LAST_CHANGE"; } else { throw new CdpException("Unsupported OS found - " + OS); } try { URL u = new URL(url); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); if (conn.getResponseCode() != 200) { throw new CdpException(conn.getResponseCode() + " - " + conn.getResponseMessage()); } String result = null; try (Scanner s = new Scanner(conn.getInputStream())) { s.useDelimiter("\\A"); result = s.hasNext() ? s.next() : ""; } return new ChromiumVersion(Integer.parseInt(result)); } catch (IOException e) { throw new CdpException(e); } }
From source file:org.openbmap.soapclient.CheckServerTask.java
/** * Checks connection to openbmap.org/*ww w. j a va 2 s. c o m*/ * @return true on successful http connection */ private static boolean isOnline() { try { Log.v(TAG, "Ping " + Preferences.VERSION_CHECK_URL); final URL url = new URL(Preferences.VERSION_CHECK_URL); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Connection", "close"); connection.setConnectTimeout(CONNECTION_TIMEOUT); connection.connect(); if (connection.getResponseCode() == 200) { Log.i(TAG, String.format("Good: Server reply %s - device & server online", connection.getResponseCode())); return true; } else { Log.w(TAG, String.format("Bad: Http ping failed (server reply %s).", connection.getResponseCode())); } } catch (final IOException e) { Log.w(TAG, "Bad: Http ping failed (no response).."); } return false; }
From source file:net.kourlas.voipms_sms.Utils.java
/** * Retrieves a JSON object from the specified URL. * <p/>//from ww w . ja v a 2s .c o m * Note that this is a blocking method; it should not be called from the URI thread. * * @param urlString The URL to retrieve the JSON from. * @return The JSON object at the specified URL. * @throws IOException if a connection to the server could not be established. * @throws JSONException if the server did not return valid JSON. */ public static JSONObject getJson(String urlString) throws IOException, JSONException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(10000); connection.setConnectTimeout(15000); connection.setRequestMethod("GET"); connection.setDoInput(true); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); StringBuilder data = new StringBuilder(); String newLine = System.getProperty("line.separator"); String line; while ((line = reader.readLine()) != null) { data.append(line); data.append(newLine); } reader.close(); return new JSONObject(data.toString()); }
From source file:a122016.rr.com.alertme.QueryUtils.java
/** * Make an HTTP request to the given URL and return a String as the response. *///from w w w. jav a 2s.c o m private static String makeHttpRequest(URL url) throws IOException { String jsonResponse = ""; // If the URL is null, then return early. if (url == null) { return jsonResponse; } HttpURLConnection urlConnection = null; InputStream inputStream = null; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReadTimeout(10000 /* milliseconds */); urlConnection.setConnectTimeout(15000 /* milliseconds */); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // If the request was successful (response code 200), // then read the input stream and parse the response. if (urlConnection.getResponseCode() == 200) { inputStream = urlConnection.getInputStream(); jsonResponse = readFromStream(inputStream); } else { Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode()); } } catch (IOException e) { Log.e(LOG_TAG, "Problem retrieving the Places JSON results.", e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (inputStream != null) { // Closing the input stream could throw an IOException, which is why // the makeHttpRequest(URL url) method signature specifies than an IOException // could be thrown. inputStream.close(); } } return jsonResponse; }
From source file:mashberry.com500px.util.Api_Parser.java
/******************************************************************************* * //from w w w . j a v a 2 s.c o m * ( ) * *******************************************************************************/ public static String get_first_detail(final String url_feature, final int url_image_size, final String url_category, final int url_page, int image_no) { String returnStr = "success"; String urlStr = DB.Get_Photo_Url + "?feature=" + url_feature + "&image_size=" + url_image_size + "&only=" + getCategoryName(url_category) + "&page=" + url_page + "&consumer_key=" + Var.consumer_key + "&rpp=" + image_no; try { URL url = new URL(urlStr); URLConnection uc = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) uc; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setConnectTimeout(10000); httpConn.setRequestMethod("GET"); httpConn.connect(); int response = httpConn.getResponseCode(); Main.progressBar_process(50); if (response == HttpURLConnection.HTTP_OK) { InputStream in = httpConn.getInputStream(); String smallImageOpt = "3"; // (8 1/8 ) String largeImageOpt = "0"; String userPictureOpt = "8"; String result = convertStreamToString(in); JSONObject jObject = new JSONObject(result); JSONArray jsonArray = jObject.getJSONArray("photos"); Main.progressBar_process(75); if (jsonArray.length() == 0) { returnStr = "no results"; } else { for (int i = 0; i < jsonArray.length(); i++) { Var.categoryArr.add(jsonArray.getJSONObject(i).getString("category")); Var.idArr.add(jsonArray.getJSONObject(i).getString("id")); String smallImage = jsonArray.getJSONObject(i).getString("image_url"); String largeImage = largeImageOpt + smallImage.substring(0, smallImage.lastIndexOf(".jpg") - 1) + "4.jpg"; Var.imageSmall_urlArr.add(smallImageOpt + smallImage); Var.imageLarge_urlArr.add(largeImage); Var.nameArr.add(jsonArray.getJSONObject(i).getString("name")); Var.ratingArr.add(jsonArray.getJSONObject(i).getString("rating")); JSONObject jsonuser = jsonArray.getJSONObject(i).getJSONObject("user"); Var.user_firstnameArr.add(jsonuser.getString("firstname")); Var.user_fullnameArr.add(jsonuser.getString("fullname")); Var.user_lastnameArr.add(jsonuser.getString("lastname")); Var.user_upgrade_statusArr.add(jsonuser.getString("upgrade_status")); Var.user_usernameArr.add(jsonuser.getString("username")); Var.user_userpic_urlArr.add(userPictureOpt + jsonuser.getString("userpic_url")); Main.progressBar_process(75 + (15 * i / jsonArray.length())); } } // Log.i("Main", "urlStr " +urlStr); // Log.i("Main", "url_feature " +url_feature); // Log.i("Main", "categoryArr " +Var.categoryArr); // Log.i("Main", "idArr " +Var.idArr); // Log.i("Main", "imageLarge_urlArr " +Var.imageLarge_urlArr); // Log.i("Main", "nameArr " +Var.nameArr); // Log.i("Main", "ratingArr " +Var.ratingArr); // Log.i("Main", "user_firstnameArr " +Var.user_firstnameArr); // Log.i("Main", "user_fullnameArr " +Var.user_fullnameArr); // Log.i("Main", "user_lastnameArr " +Var.user_lastnameArr); // Log.i("Main", "user_upgrade_statusArr " +Var.user_upgrade_statusArr); // Log.i("Main", "user_usernameArr " +Var.user_usernameArr); // Log.i("Main", "user_userpic_urlArr " +Var.user_userpic_urlArr); } else { returnStr = "not response"; return returnStr; } } catch (Exception e) { e.printStackTrace(); returnStr = "not response"; return returnStr; } return returnStr; }
From source file:dictinsight.utils.io.HttpUtils.java
public static List<String> getSvnConfServer(String url) { BufferedReader reader = null; HttpURLConnection connection = null; List<String> seedList = new ArrayList<String>(); try {/* w ww. ja v a 2s . c om*/ URL srcUrl = new URL(url); connection = (HttpURLConnection) srcUrl.openConnection(); connection.setConnectTimeout(1000 * 10); connection.connect(); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String rec; while ((rec = reader.readLine()) != null) { seedList.add(rec); } } catch (Exception e) { System.out.println("get date from " + url + " error!"); e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (connection != null) connection.disconnect(); } return seedList; }
From source file:com.magnet.tools.tests.MagnetToolStepDefs.java
public static boolean ping(String url, int maxSecs) { long startMs = System.currentTimeMillis(); try {// w w w . jav a2s .c o m while (maxSecs >= ((System.currentTimeMillis() - startMs) / 1000)) { try { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode(); if (200 <= responseCode && responseCode <= 399) { return true; } else { Thread.sleep(2000); } } catch (IOException exception) { Thread.sleep(2000); } } } catch (InterruptedException ie) { // IGNORE } return false; }