List of usage examples for java.net URLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:com.pursuer.reader.easyrss.WebpageItemViewCtrl.java
@SuppressLint("SimpleDateFormat") private void showMobilizedPage() { showMobilized = true;/* w w w . j a v a2s. co m*/ view.findViewById(R.id.Mobilized).setVisibility(View.VISIBLE); view.findViewById(R.id.OriginalContent).setVisibility(View.GONE); view.findViewById(R.id.BtnMobilzedPage).setEnabled(false); view.findViewById(R.id.BtnOriginalPage).setEnabled(true); view.findViewById(R.id.OriginalProgress).setVisibility(View.GONE); view.findViewById(R.id.MobilizedProgress).setVisibility(View.VISIBLE); view.findViewById(R.id.MobilizedContent).setVisibility(View.GONE); final TextView title = (TextView) view.findViewById(R.id.ItemTitle); title.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize * 4 / 3); title.setText(item.getTitle()); final TextView info = (TextView) view.findViewById(R.id.ItemInfo); info.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize * 4 / 5); final StringBuilder infoText = new StringBuilder(); final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); sdf.setTimeZone(TimeZone.getDefault()); infoText.append(sdf.format(Utils.timestampToDate(item.getTimestamp()))); if (item.getAuthor() != null && item.getAuthor().length() > 0) { infoText.append(" | By "); infoText.append(item.getAuthor()); } if (item.getSourceTitle() != null && item.getSourceTitle().length() > 0) { infoText.append(" ("); infoText.append(item.getSourceTitle()); infoText.append(")"); } info.setText(infoText); if (thread == null) { thread = new Thread(new Runnable() { @SuppressWarnings("deprecation") @Override public void run() { try { final StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append("http://easyrss.pursuer.me/parser?url="); urlBuilder.append(URLEncoder.encode(item.getHref())); urlBuilder.append("&email="); urlBuilder.append(URLEncoder.encode(dataMgr.getSettingByName(Setting.SETTING_USERNAME))); urlBuilder.append("&version="); urlBuilder.append(context.getString(R.string.Version)); final URLConnection connection = new URL(urlBuilder.toString()).openConnection(); connection.setConnectTimeout(30 * 1000); connection.setReadTimeout(20 * 1000); final InputStreamReader input = new InputStreamReader(connection.getInputStream()); final StringBuilder builder = new StringBuilder(); final char buff[] = new char[8192]; int len; while ((len = input.read(buff)) != -1) { builder.append(new String(buff, 0, len)); } builder.append(theme == SettingTheme.THEME_NORMAL ? DataUtils.DEFAULT_NORMAL_CSS : DataUtils.DEFAULT_DARK_CSS); pageContent = builder.toString(); handler.sendMessage(handler.obtainMessage(MSG_LOADING_FINISHED, WebpageItemViewCtrl.this)); } catch (final MalformedURLException exception) { exception.printStackTrace(); pageContent = genFailedToLoadContentPage(context, theme); handler.sendMessage(handler.obtainMessage(MSG_LOADING_FINISHED, WebpageItemViewCtrl.this)); } catch (final IOException exception) { exception.printStackTrace(); pageContent = genFailedToLoadContentPage(context, theme); handler.sendMessage(handler.obtainMessage(MSG_LOADING_FINISHED, WebpageItemViewCtrl.this)); } } }); thread.setPriority(Thread.MIN_PRIORITY); thread.start(); } else if (!thread.isAlive()) { handler.sendMessage(handler.obtainMessage(MSG_LOADING_FINISHED, WebpageItemViewCtrl.this)); } }
From source file:org.transitime.avl.PollUrlAvlModule.java
/** * Actually reads data from feed and processes it by opening up a URL * specified by getUrl() and then reading the contents. Calls the abstract * method processData() to actually process the input stream. * <p>/*from w w w . j av a2 s . c om*/ * This method needs to be overwritten if not real data from a URL * * @throws Exception * Throws a generic exception since the processing is done in * the abstract method processData() and it could throw any type * of exception since we don't really know how the AVL feed will * be processed. */ protected void getAndProcessData() throws Exception { // For logging IntervalTimer timer = new IntervalTimer(); // Get from the AVL feed subclass the URL to use for this feed String fullUrl = getUrl(); // Log what is happening logger.info("Getting data from feed using url=" + fullUrl); // Create the connection URL url = new URL(fullUrl); URLConnection con = url.openConnection(); // Set the timeout so don't wait forever int timeoutMsec = AvlConfig.getAvlFeedTimeoutInMSecs(); con.setConnectTimeout(timeoutMsec); con.setReadTimeout(timeoutMsec); // Request compressed data to reduce bandwidth used if (useCompression) con.setRequestProperty("Accept-Encoding", "gzip,deflate"); // If authentication being used then set user and password if (authenticationUser.getValue() != null && authenticationPassword.getValue() != null) { String authString = authenticationUser.getValue() + ":" + authenticationPassword.getValue(); byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); con.setRequestProperty("Authorization", "Basic " + authStringEnc); } // Set any additional AVL feed specific request headers setRequestHeaders(con); // Create appropriate input stream depending on whether content is // compressed or not InputStream in = con.getInputStream(); if ("gzip".equals(con.getContentEncoding())) { in = new GZIPInputStream(in); logger.debug("Returned data is compressed"); } else { logger.debug("Returned data is NOT compressed"); } // For debugging logger.debug("Time to access inputstream {} msec", timer.elapsedMsec()); // Call the abstract method to actually process the data timer.resetTimer(); Collection<AvlReport> avlReportsReadIn = processData(in); in.close(); logger.debug("Time to parse document {} msec", timer.elapsedMsec()); // Process all the reports read in if (shouldProcessAvl.getValue()) processAvlReports(avlReportsReadIn); }
From source file:com.oakesville.mythling.util.HttpHelper.java
private void prepareConnection(URLConnection conn, Map<String, String> headers) throws IOException { conn.setConnectTimeout(getConnectTimeout()); conn.setReadTimeout(getReadTimeout()); for (String key : headers.keySet()) conn.setRequestProperty(key, headers.get(key)); if (method == Method.Post) { ((HttpURLConnection) conn).setRequestMethod("POST"); if (postContent != null) conn.setDoOutput(true);/*www. j a va 2s . c o m*/ } }
From source file:com.controller.CuotasController.java
@RequestMapping("cuotas.htm") public ModelAndView getCuotas(HttpServletRequest request) { sesion = request.getSession();/*from w ww . j av a 2 s.co m*/ ModelAndView mav = new ModelAndView(); String mensaje = null; Detalles detalle = (Detalles) sesion.getAttribute("cuenta"); String country = detalle.getCiudad(); String amount = "5"; String myURL = "http://192.168.5.39/app_dev.php/public/get/rates"; // System.out.println("Requested URL:" + myURL); StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null; try { URL url = new URL(myURL); urlConn = url.openConnection(); if (urlConn != null) { urlConn.setReadTimeout(60 * 1000); urlConn.setDoOutput(true); String data = URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8"); data += "&" + URLEncoder.encode("amount", "UTF-8") + "=" + URLEncoder.encode(amount, "UTF-8"); System.out.println("los Datos a enviar por POST son " + data); try ( //obtenemos el flujo de escritura OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) { //escribimos wr.write(data); wr.flush(); //cerramos la conexin } } if (urlConn != null && urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) { int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Exception while calling URL:" + myURL, e); } String resultado = sb.toString(); if (sesion.getAttribute("usuario") == null) { mav.setViewName("login/login"); } else { sesionUser = sesion.getAttribute("usuario").toString(); //Detalles detalle = (Detalles) sesion.getAttribute("cuenta"); mav.addObject("country", detalle.getCiudad()); mav.addObject("resultado", resultado); if (sesion.getAttribute("tipoUsuario").toString().compareTo("Administrador") == 0) { mav.setViewName("viewsAdmin/cuotasAdmin"); System.out.println("el usuario es administrador"); } else { mav.setViewName("panel/cuotas"); } } return mav; }
From source file:com.controller.CuotasController.java
@RequestMapping("cuotasAdmin.htm") public ModelAndView getCuotasAdmin(HttpServletRequest request) { sesion = request.getSession();/*ww w . j a v a2 s.com*/ ModelAndView mav = new ModelAndView(); String mensaje = null; Detalles detalle = (Detalles) sesion.getAttribute("cuenta"); String country = detalle.getCiudad(); String amount = "5"; String myURL = "http://192.168.5.39/app_dev.php/public/get/rates"; // System.out.println("Requested URL:" + myURL); StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null; try { URL url = new URL(myURL); urlConn = url.openConnection(); if (urlConn != null) { urlConn.setReadTimeout(60 * 1000); urlConn.setDoOutput(true); String data = URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8"); data += "&" + URLEncoder.encode("amount", "UTF-8") + "=" + URLEncoder.encode(amount, "UTF-8"); System.out.println("los Datos a enviar por POST son " + data); try ( //obtenemos el flujo de escritura OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) { //escribimos wr.write(data); wr.flush(); //cerramos la conexin } } if (urlConn != null && urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) { int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Exception while calling URL:" + myURL, e); } String resultado = sb.toString(); if (sesion.getAttribute("usuario") == null) { mav.setViewName("login/login"); } else { sesionUser = sesion.getAttribute("usuario").toString(); //Detalles detalle = (Detalles) sesion.getAttribute("cuenta"); mav.addObject("country", detalle.getCiudad()); mav.addObject("resultado", resultado); if (sesion.getAttribute("tipoUsuario").toString().compareTo("Administrador") == 0) { mav.setViewName("viewsAdmin/cuotasAdmin"); System.out.println("el usuario es administrador"); } else { mav.setViewName("panel/cuotas"); } } return mav; }
From source file:com.util.httpAccount.java
public Account getAccountObject(String tel) { String telefono = tel.replace("-", ""); System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON"); //String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/50241109321.json"; String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/" + telefono + ".json"; System.out.println("Requested URL:" + myURL); StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null;// w w w . j a v a 2s. c o m Account account = new Account(); try { URL url = new URL(myURL); urlConn = url.openConnection(); if (urlConn != null) { urlConn.setReadTimeout(60 * 1000); if (urlConn != null && urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) { int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } } String jsonResult = sb.toString(); // System.out.println(sb.toString()); //System.out.println("\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n"); JSONObject objJason = new JSONObject(jsonResult); JSONArray dataJson = new JSONArray(); dataJson = objJason.getJSONArray("data"); //System.out.println("objeto normal 1 "+dataJson.toString()); // // // System.out.println("\n\n--------------------CREAMOS UN STRING JSON2 REEMPLAZANDO LOS CORCHETES QUE DAN ERROR---------------------------\n\n"); String jsonString2 = dataJson.toString(); String temp = dataJson.toString(); temp = jsonString2.replace("[", ""); jsonString2 = temp.replace("]", ""); // System.out.println("new json string"+jsonString2); JSONObject objJson2 = new JSONObject(jsonString2); // System.out.println("el objeto simple json es " + objJson2.toString()); // System.out.println("\n\n--------------------CREAMOS UN OBJETO JSON CON EL ARRAR ACCOUN---------------------------\n\n"); String account1 = objJson2.optString("account"); // System.out.println(account1); JSONObject objJson3 = new JSONObject(account1); // System.out.println("el ULTIMO OBJETO SIMPLE ES " + objJson3.toString()); // System.out.println("\n\n--------------------EMPEZAMOS A RECIBIR LOS PARAMETROS QUE HAY EN EL OBJETO JSON---------------------------\n\n"); String firstName = objJson3.getString("first_name"); System.out.println(firstName); System.out.println(objJson3.get("language_id")); // System.out.println("\n\n--------------------TRATAMOS DE PASAR TODO EL ACCOUNT A OBJETO JAVA---------------------------\n\n"); Gson gson = new Gson(); account = gson.fromJson(objJson3.toString(), Account.class); //System.out.println(account.getFirst_name()); // System.out.println(account.getCreation()); account.setLanguaje_id(objJson3.get("language_id").toString()); account.setId(objJson3.get("id").toString()); account.setBalance(objJson3.get("balance").toString()); System.out.println("el id del account es " + account.getId()); } else { System.out.print("no se pudo conectar con el servidor"); account = null; } in.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Exception while calling URL:" + myURL, e); } return account; }
From source file:com.controller.CuotasController.java
@RequestMapping(value = "postCuotas.htm", method = RequestMethod.POST) public ModelAndView postCuotas(HttpServletRequest request) { sesion = request.getSession();//from w w w . j a va 2 s .c om String country = request.getParameter("country"); String amount = request.getParameter("amount"); Detalles detalle = (Detalles) sesion.getAttribute("cuenta"); System.out.print(detalle.getCiudad()); String myURL = "http://192.168.5.39/app_dev.php/public/get/rates"; // System.out.println("Requested URL:" + myURL); StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null; try { URL url = new URL(myURL); urlConn = url.openConnection(); if (urlConn != null) { urlConn.setReadTimeout(60 * 1000); urlConn.setDoOutput(true); String data = URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8"); data += "&" + URLEncoder.encode("amount", "UTF-8") + "=" + URLEncoder.encode(amount, "UTF-8"); System.out.println("los Datos a enviar por POST son " + data); try ( //obtenemos el flujo de escritura OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) { //escribimos wr.write(data); wr.flush(); //cerramos la conexin } } if (urlConn != null && urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) { int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Exception while calling URL:" + myURL, e); } String resultado = sb.toString(); ModelAndView mav = new ModelAndView(); if (sesion.getAttribute("usuario") == null) { mav.setViewName("login/login"); } else { sesionUser = sesion.getAttribute("usuario").toString(); //Detalles detalle = (Detalles) sesion.getAttribute("cuenta"); mav.addObject("country", detalle.getCiudad()); mav.addObject("resultado", resultado); if (sesion.getAttribute("tipoUsuario").toString().compareTo("Administrador") == 0) { mav.setViewName("viewsAdmin/cuotasAdmin"); System.out.println("el usuario es administrador"); } else { mav.setViewName("panel/cuotas"); } } return mav; }
From source file:msearch.io.MSFilmlisteLesen.java
private boolean filmlisteDownload(String uurl, File nachDatei) { boolean ret = false; try {//from w w w. j a v a 2 s . c o m URLConnection conn = new URL(uurl).openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); conn.setRequestProperty("User-Agent", MSConfig.getUserAgent()); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); FileOutputStream fOut; byte[] buffer = new byte[1024]; int n = 0; int count = 0; int countMax; if (uurl.endsWith(MSConst.FORMAT_XZ) || uurl.endsWith(MSConst.FORMAT_BZ2) || uurl.endsWith(MSConst.FORMAT_ZIP)) { countMax = 44; } else { countMax = 250; } fOut = new FileOutputStream(nachDatei); this.notifyProgress(uurl); while (!MSConfig.getStop() && (n = in.read(buffer)) != -1) { fOut.write(buffer, 0, n); ++count; if (count > countMax) { this.notifyProgress(uurl); count = 0; } } if (MSConfig.getStop()) { ret = false; } else { ret = true; } try { fOut.close(); in.close(); } catch (Exception e) { } } catch (Exception ex) { MSLog.fehlerMeldung(952163678, MSLog.FEHLER_ART_PROG, "MSearchIoXmlFilmlisteLesen.filmlisteDownload", ex); } return ret; }
From source file:com.servoy.extension.MarketPlaceExtensionProvider.java
private URLConnection ws_getConnection(String action, String acceptContentType, String extensionId, String version) throws Exception { String unescapedURL = MARKETPLACE_WS + action + "/" + extensionId //$NON-NLS-1$ + (version != null ? "/" + version : "")/* + "?nodebug=true" */; //$NON-NLS-1$ //$NON-NLS-2$ URL mpURL = new URI(null, null, unescapedURL, null).toURL(); // the URI should escape it correctly URLConnection urlConnection = mpURL.openConnection(); urlConnection.addRequestProperty("accept", acceptContentType); //$NON-NLS-1$ urlConnection.setConnectTimeout(30 * 1000); // don't make an unstoppable job if the network connection is down urlConnection.setReadTimeout(30 * 1000); // don't make an unstoppable job if the network connection is down or server doesn't want to respond return urlConnection; }
From source file:de.mango.business.GoogleSearchProvider.java
public Vector<String> search(String query, int count, int page) { Vector<String> results = new Vector<String>(); // Prepare the query try {/*from w ww .j a va 2s .c o m*/ query = "http://ajax.googleapis.com/ajax/services/search/images?" + GoogleSearchProvider.searchArguments + this.hostLanguage + "&q=" + URLEncoder.encode( GoogleSearchProvider.restrictToOpenClipart ? query + GoogleSearchProvider.openClipart : query, "UTF-8") + "&start="; } catch (UnsupportedEncodingException e) { if (DEBUG) { Log.w(TAG, "Unsupported Encoding Exception:" + e.getMessage()); Log.w(TAG, Log.getStackTraceString(e)); } return results; } // start argument to pass to google int firstindex = count * page; // count of results to skip before adding them to the result array int skip = 0; // start indices > 56 are skipped by Google, so we // ask for results from 56, but skip the unwanted $skip indices if (firstindex > 63) return results; if (firstindex > 56) { skip = firstindex - 56; firstindex = 56; } boolean readMore = true; // do we need more queries and are they // possible? while (readMore) { // add start index to the query String currentQuery = query + firstindex; if (DEBUG) Log.d(TAG, "Searching: " + currentQuery); try { // prepare the connection URL url = new URL(currentQuery); URLConnection connection = url.openConnection(); connection.addRequestProperty("Referer", GoogleSearchProvider.refererUrl); connection.setConnectTimeout(2000); connection.setReadTimeout(2000); connection.connect(); // receive the results StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { builder.append(line); } // parse the results JSONObject json = new JSONObject(builder.toString()); int responseStatus = json.getInt("responseStatus"); if (responseStatus == 200)// successful search { json = json.getJSONObject("responseData"); JSONArray res = json.getJSONArray("results"); if (res.length() == 0) return results; String s; int limit = Math.min(res.length(), count - results.size() + skip); for (int i = skip; i < limit; i++) { s = res.getJSONObject(i).getString("unescapedUrl"); if (s != null) results.addElement(s); } // see if there are "more Results" JSONObject cursor = json.getJSONObject("cursor"); JSONArray pages = cursor.getJSONArray("pages"); int pageCount = pages.length(); int currentPageIndex = cursor.getInt("currentPageIndex"); this.moreResults = readMore = (pageCount - 1) > currentPageIndex; } else { if (DEBUG) Log.w(TAG, "Goole Search Error (Code " + responseStatus + "):" + json.getString("responseDetails")); this.moreResults = readMore = false;// prevent for (;;) loop // on errors } } catch (MalformedURLException e) { if (DEBUG) { Log.w(TAG, "MalformedURLException:" + e.getMessage()); Log.w(TAG, Log.getStackTraceString(e)); } this.moreResults = readMore = false; } catch (IOException e) { if (DEBUG) { Log.w(TAG, "IOException:" + e.getMessage()); Log.w(TAG, Log.getStackTraceString(e)); } this.moreResults = readMore = false; } catch (JSONException e) { if (DEBUG) { Log.w(TAG, "JSONException:" + e.getMessage()); Log.w(TAG, Log.getStackTraceString(e)); } this.moreResults = readMore = false; } // read more only if we can read more AND want to have more readMore = readMore && results.size() < count; if (readMore) { firstindex += 8; if (firstindex > 56)// the last pages always need to start // querying at index 56 (or google returns // errors) { skip = firstindex - 56; firstindex = 56; } } } return results; }