List of usage examples for java.net HttpURLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:com.sandklef.coachapp.http.HttpAccess.java
public void downloadVideo(String clubUri, String file, String videoUuid) throws HttpAccessException { try {//from w w w. j ava 2 s. c o m //$ GET http://localhost:3000/v0.0.0/clubs/<ID>/videos/uuid/<ID>/download // String file = LocalStorage.getInstance().getDownloadMediaDir() + "/" + videoUuid + SERVER_VIDEO_SUFFIX; int TIMEOUT_CONNECTION = 5000;//5sec int TIMEOUT_SOCKET = 30000;//30sec String urlServer = urlBase + HttpSettings.API_VERSION + HttpSettings.PATH_SEPARATOR + HttpSettings.VIDEO_URL_PATH + HttpSettings.UUID_PATH + videoUuid + HttpSettings.PATH_SEPARATOR + HttpSettings.DOWNLOAD_PATH; /* String urlServer = urlBase + HttpSettings.API_VERSION + HttpSettings.CLUB_PATH + HttpSettings.PATH_SEPARATOR + clubUri + HttpSettings.PATH_SEPARATOR + HttpSettings.VIDEO_URL_PATH + HttpSettings.UUID_PATH + videoUuid + HttpSettings.PATH_SEPARATOR + HttpSettings.DOWNLOAD_PATH ; */ URL url = new URL(urlServer); long startTime = System.currentTimeMillis(); Log.i(LOG_TAG, "video download beginning: " + urlServer); //Open a connection to that URL. HttpURLConnection ucon = (HttpURLConnection) url.openConnection(); ucon.setRequestProperty("X-Token", LocalStorage.getInstance().getLatestUserToken()); ucon.addRequestProperty("X-Instance", LocalStorage.getInstance().getCurrentClub()); ucon.setRequestMethod(HttpSettings.HTTP_GET); //this timeout affects how long it takes for the app to realize there's a connection problem ucon.setReadTimeout(TIMEOUT_CONNECTION); ucon.setConnectTimeout(TIMEOUT_SOCKET); Log.d(LOG_TAG, " and now to ...1"); //Define InputStreams to read from the HttpURLConnection // uses 3KB download buffer InputStream is = ucon.getInputStream(); Log.d(LOG_TAG, " and now to ...1"); BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5); Log.d(LOG_TAG, " and now to ...2 to file: " + file); FileOutputStream outStream = new FileOutputStream(file); Log.d(LOG_TAG, " and now to ..31"); byte[] buff = new byte[5 * 1024]; System.err.println("For those about to ... file: " + file); //Read bytes (and store them) until there is nothing more to read(-1) int len; while ((len = inStream.read(buff)) != -1) { outStream.write(buff, 0, len); } Log.d(LOG_TAG, "response code: " + ucon.getResponseCode()); //clean up outStream.flush(); outStream.close(); inStream.close(); Log.d(LOG_TAG, "For those about to ..."); Log.d(LOG_TAG, "download completed in " + ((System.currentTimeMillis() - startTime) / 1000) + " sec"); if (!HttpSettings.isResponseOk(ucon.getResponseCode())) { throw new HttpAccessException( "Failed downloading video, response from server " + ucon.getResponseCode(), HttpAccessException.ACCESS_ERROR); } } catch (FileNotFoundException e) { e.printStackTrace(); throw new HttpAccessException("Failed downloading video", e, HttpAccessException.FILE_NOT_FOUND); } catch (Exception e) { e.printStackTrace(); throw new HttpAccessException("Failed downloading video", e, HttpAccessException.NETWORK_ERROR); } }
From source file:com.google.zxing.web.DecodeServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String imageURIString = request.getParameter("u"); if (imageURIString == null || imageURIString.isEmpty()) { log.info("URI was empty"); response.sendRedirect("badurl.jspx"); return;/* w ww . ja v a2 s. c o m*/ } imageURIString = imageURIString.trim(); for (CharSequence substring : blockedURLSubstrings) { if (imageURIString.contains(substring)) { log.info("Disallowed URI " + imageURIString); response.sendRedirect("badurl.jspx"); return; } } URI imageURI; try { imageURI = new URI(imageURIString); // Assume http: if not specified if (imageURI.getScheme() == null) { imageURI = new URI("http://" + imageURIString); } } catch (URISyntaxException urise) { log.info("URI " + imageURIString + " was not valid: " + urise); response.sendRedirect("badurl.jspx"); return; } // Shortcut for data URI if ("data".equals(imageURI.getScheme())) { try { BufferedImage image = ImageReader.readDataURIImage(imageURI); processImage(image, request, response); } catch (IOException ioe) { log.info(ioe.toString()); response.sendRedirect("badurl.jspx"); } return; } URL imageURL; try { imageURL = imageURI.toURL(); } catch (MalformedURLException ignored) { log.info("URI was not valid: " + imageURIString); response.sendRedirect("badurl.jspx"); return; } String protocol = imageURL.getProtocol(); if (!"http".equalsIgnoreCase(protocol) && !"https".equalsIgnoreCase(protocol)) { log.info("URI was not valid: " + imageURIString); response.sendRedirect("badurl.jspx"); return; } HttpURLConnection connection; try { connection = (HttpURLConnection) imageURL.openConnection(); } catch (IllegalArgumentException ignored) { log.info("URI could not be opened: " + imageURL); response.sendRedirect("badurl.jspx"); return; } connection.setAllowUserInteraction(false); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); connection.setRequestProperty(HttpHeaders.USER_AGENT, "zxing.org"); connection.setRequestProperty(HttpHeaders.CONNECTION, "close"); try { connection.connect(); } catch (IOException ioe) { // Encompasses lots of stuff, including // java.net.SocketException, java.net.UnknownHostException, // javax.net.ssl.SSLPeerUnverifiedException, // org.apache.http.NoHttpResponseException, // org.apache.http.client.ClientProtocolException, log.info(ioe.toString()); response.sendRedirect("badurl.jspx"); return; } try (InputStream is = connection.getInputStream()) { try { if (connection.getResponseCode() != HttpServletResponse.SC_OK) { log.info("Unsuccessful return code: " + connection.getResponseCode()); response.sendRedirect("badurl.jspx"); return; } if (connection.getHeaderFieldInt(HttpHeaders.CONTENT_LENGTH, 0) > MAX_IMAGE_SIZE) { log.info("Too large"); response.sendRedirect("badimage.jspx"); return; } log.info("Decoding " + imageURL); processStream(is, request, response); } finally { consumeRemainder(is); } } catch (IOException ioe) { log.info(ioe.toString()); response.sendRedirect("badurl.jspx"); } finally { connection.disconnect(); } }
From source file:com.conx.logistics.kernel.bpm.impl.jbpm.core.mock.BPMGuvnorUtil.java
public String getFormTemplateURLFromGuvnor(String templateName, String format) { List<String> allPackages = getPackageNames(); try {//from w ww . j ava2 s . co m for (String pkg : allPackages) { String templateURL = getGuvnorProtocol() + "://" + getGuvnorHost() + "/" + getGuvnorSubdomain() + "/rest/packages/" + pkg + "/assets/" + URLEncoder.encode(templateName, "UTF-8"); URL checkURL = new URL(templateURL); HttpURLConnection checkConnection = (HttpURLConnection) checkURL.openConnection(); checkConnection.setRequestMethod("GET"); checkConnection.setRequestProperty("Accept", "application/atom+xml"); checkConnection.setConnectTimeout(Integer.parseInt(getGuvnorConnectTimeout())); checkConnection.setReadTimeout(Integer.parseInt(getGuvnorReadTimeout())); applyAuth(checkConnection); checkConnection.connect(); if (checkConnection.getResponseCode() == 200) { String toReturnURL = getGuvnorProtocol() + "://" + getGuvnorHost() + "/" + getGuvnorSubdomain() + "/org.drools.guvnor.Guvnor/package/" + pkg + "/" + getGuvnorSnapshotName() + "/" + URLEncoder.encode(templateName, "UTF-8") + "." + format; return toReturnURL; } } } catch (Exception e) { logger.error("Exception returning template url : " + e.getMessage()); return null; } logger.info("Could not find process template url for: " + templateName); return null; }
From source file:com.licryle.httpposter.HttpPoster.java
/** * Opens a connection to the POST end point specified in the mConf * {@link HttpConfiguration} and sends the content of mEntity. Attempts to * read the answer from the server after the POST Request. * // ww w. ja v a 2 s .c om * @param mConf The {@link HttpConfiguration} of the request. * @param mEntity The Entity to send in the HTTP Post. Should be built using * {@link #_buildEntity}. * * @return The result of the HTTP Post request. Either #SUCCESS, * #FAILURE_CONNECTION, #FAILURE_TRANSFER, #FAILURE_RESPONSE, * #FAILURE_MALFORMEDURL. * * @see HttpConfiguration * @see _ProgressiveEntity */ protected Long _httpPost(HttpConfiguration mConf, _ProgressiveEntity mEntity) { Log.d("HttpPoster", String.format("_httpPost: Entering Instance %d", _iInstanceId)); /******** Open request ********/ try { HttpURLConnection mConn = (HttpURLConnection) mConf.getEndPoint().openConnection(); mConn.setRequestMethod("POST"); mConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + mConf.getHTTPBoundary()); mConn.setDoInput(true); mConn.setDoOutput(true); mConn.setUseCaches(false); mConn.setReadTimeout(mConf.getReadTimeout()); mConn.setConnectTimeout(mConf.getConnectTimeout()); mConn.setInstanceFollowRedirects(false); mConn.connect(); Log.d("HttpPoster", String.format("_httpPost: Connected for Instance %d", _iInstanceId)); try { /********** Write request ********/ _dispatchOnStartTransfer(); Log.d("HttpPoster", String.format("_httpPost: Sending for Instance %d", _iInstanceId)); mEntity.writeTo(mConn.getOutputStream()); mConn.getOutputStream().flush(); mConn.getOutputStream().close(); _iResponseCode = mConn.getResponseCode(); try { Log.d("HttpPoster", String.format("_httpPost: Reading for Instance %d", _iInstanceId)); _readServerAnswer(mConn.getInputStream()); return SUCCESS; } catch (IOException e) { return FAILURE_RESPONSE; } } catch (Exception e) { Log.d("HTTPParser", e.getMessage()); e.printStackTrace(); return FAILURE_TRANSFER; } finally { if (mConn != null) { Log.d("HttpPoster", String.format("_httpPost: Disconnecting Instance %d", _iInstanceId)); mConn.disconnect(); } } } catch (Exception e) { return FAILURE_CONNECTION; } }
From source file:com.conx.logistics.kernel.bpm.impl.jbpm.core.mock.BPMGuvnorUtil.java
public boolean templateExistsInRepo(String templateName) throws Exception { List<String> allPackages = getPackageNames(); try {/*from w w w . ja v a 2s . co m*/ for (String pkg : allPackages) { String templateURL = getGuvnorProtocol() + "://" + getGuvnorHost() + "/" + getGuvnorSubdomain() + "/rest/packages/" + pkg + "/assets/" + URLEncoder.encode(templateName, "UTF-8"); URL checkURL = new URL(templateURL); HttpURLConnection checkConnection = (HttpURLConnection) checkURL.openConnection(); checkConnection.setRequestMethod("GET"); checkConnection.setRequestProperty("Accept", "application/atom+xml"); checkConnection.setConnectTimeout(Integer.parseInt(getGuvnorConnectTimeout())); checkConnection.setReadTimeout(Integer.parseInt(getGuvnorReadTimeout())); applyAuth(checkConnection); checkConnection.connect(); if (checkConnection.getResponseCode() == 200) { XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader reader = factory.createXMLStreamReader(checkConnection.getInputStream()); boolean foundFormFormat = false; while (reader.hasNext()) { if (reader.next() == XMLStreamReader.START_ELEMENT) { if ("format".equals(reader.getLocalName())) { reader.next(); String pname = reader.getElementText(); if ("flt".equalsIgnoreCase(pname)) { foundFormFormat = true; break; } } } } return foundFormFormat; } } } catch (Exception e) { logger.error("Exception checking template url : " + e.getMessage()); return false; } logger.info("Could not find process template for: " + templateName); return false; }
From source file:csic.ceab.movelab.beepath.Util.java
public static boolean uploadFile(byte[] bytes, String filename, String uploadurl) { HttpURLConnection conn = null; DataOutputStream dos = null;// ww w.ja v a 2 s . co m // DataInputStream inStream = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 64 * 1024; // old value 1024*1024 ByteArrayInputStream byteArrayInputStream = null; boolean isSuccess = true; try { // ------------------ CLIENT REQUEST byteArrayInputStream = new ByteArrayInputStream(bytes); // open a URL connection to the Servlet URL url = new URL(uploadurl); // Open a HTTP connection to the URL conn = (HttpURLConnection) url.openConnection(); // Allow Inputs conn.setDoInput(true); // Allow Outputs conn.setDoOutput(true); // Don't use a cached copy. conn.setUseCaches(false); // set timeout conn.setConnectTimeout(60000); conn.setReadTimeout(60000); // Use a post method. conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + filename + "\"" + lineEnd); dos.writeBytes(lineEnd); // create a buffer of maximum size bytesAvailable = byteArrayInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = byteArrayInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = byteArrayInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = byteArrayInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // close streams // Log.e(TAG,"UploadService Runnable:File is written"); // fileInputStream.close(); // dos.flush(); // dos.close(); } catch (Exception e) { // Log.e(TAG, "UploadService Runnable:Client Request error", e); isSuccess = false; } finally { if (dos != null) { try { dos.close(); } catch (IOException e) { // Log.e(TAG, "exception" + e); } } if (byteArrayInputStream != null) { try { byteArrayInputStream.close(); } catch (IOException e) { // Log.e(TAG, "exception" + e); } } } // ------------------ read the SERVER RESPONSE try { if (conn.getResponseCode() != 200) { isSuccess = false; } } catch (IOException e) { // Log.e(TAG, "Connection error", e); isSuccess = false; } return isSuccess; }
From source file:com.skelril.aurora.authentication.AuthComponent.java
public synchronized JSONArray getFrom(String subAddress) { JSONArray objective = new JSONArray(); HttpURLConnection connection = null; BufferedReader reader = null; try {//from w w w .j a va2s. c o m JSONParser parser = new JSONParser(); for (int i = 1; true; i++) { try { // Establish the connection URL url = new URL(config.websiteUrl + subAddress + "?page=" + i); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(1500); connection.setReadTimeout(1500); // Check response codes return if invalid if (connection.getResponseCode() < 200 || connection.getResponseCode() >= 300) return null; // Begin to read results reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } // Parse Data JSONObject o = (JSONObject) parser.parse(builder.toString()); JSONArray ao = (JSONArray) o.get("characters"); if (ao.isEmpty()) break; Collections.addAll(objective, (JSONObject[]) ao.toArray(new JSONObject[ao.size()])); } catch (ParseException e) { break; } finally { if (connection != null) connection.disconnect(); if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } } } } catch (IOException e) { return null; } return objective; }
From source file:com.jeremyhaberman.playgrounds.WebPlaygroundDAO.java
@Override public Collection<Playground> getNearby(Context context, GeoPoint location, int maxQuantity) { playgrounds = new ArrayList<Playground>(); String result = swingset.getResources().getString(R.string.error); HttpURLConnection httpConnection = null; Log.d(TAG, "getPlaygrounds()"); try {/*from w ww .jav a2 s .com*/ // Build query URL url = new URL("http://swingsetweb.appspot.com/playground?" + TYPE_PARAM + "=" + NEARBY + "&" + LATITUDE_PARAM + "=" + location.getLatitudeE6() + "&" + LONGITUDE_PARAM + "=" + location.getLongitudeE6() + "&" + MAX_PARAM + "=" + Integer.toString(maxQuantity)); httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setConnectTimeout(15000); httpConnection.setReadTimeout(15000); StringBuilder response = new StringBuilder(); if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { // Read results from the query BufferedReader input = new BufferedReader( new InputStreamReader(httpConnection.getInputStream(), "UTF-8")); String strLine = null; while ((strLine = input.readLine()) != null) { response.append(strLine); } input.close(); } // Parse to get translated text JSONArray jsonPlaygrounds = new JSONArray(response.toString()); int numOfPlaygrounds = jsonPlaygrounds.length(); JSONObject jsonPlayground = null; for (int i = 0; i < numOfPlaygrounds; i++) { jsonPlayground = jsonPlaygrounds.getJSONObject(i); playgrounds.add(toPlayground(jsonPlayground)); } } catch (Exception e) { Log.e(TAG, "Exception", e); Intent errorIntent = new Intent(context, Playgrounds.class); errorIntent.putExtra("Exception", e.getLocalizedMessage()); errorIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); context.startActivity(errorIntent); } finally { if (httpConnection != null) { httpConnection.disconnect(); } } Log.d(TAG, " -> returned " + result); return playgrounds; }
From source file:com.seeyon.apps.m1.common.manager.menu.impl.MMenuManagerImpl.java
/** * ?HttpURLConnection?// w w w . j a va2s . c o m * * @param in * @param urlPath * @param cookies * @return * @throws Exception */ private int getNum(String urlPath) { if (urlPath == null || urlPath.length() < 10) { return 0; } HttpURLConnection httpURLConnection = null; String resulet = ""; try { URL url = new URL(urlPath);// ??? httpURLConnection = (HttpURLConnection) url.openConnection(); // ? httpURLConnection.setDoOutput(true);// httpURLConnection.setRequestMethod("get");// ?? httpURLConnection.setUseCaches(false); httpURLConnection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8"); httpURLConnection.setDoInput(true);// ? httpURLConnection.setConnectTimeout(40000); // httpURLConnection.setReadTimeout(40000);// ? httpURLConnection.connect(); if (httpURLConnection.getResponseCode() == 200) { InputStream in = httpURLConnection.getInputStream(); byte[] b = new byte[1024]; int lent = 0; while ((lent = in.read(b)) != -1) { resulet = resulet + new String(b, 0, lent); } in.close(); } return Integer.valueOf(resulet); } catch (Exception e) { e.printStackTrace(); } finally { httpURLConnection.disconnect(); } return 0; }
From source file:com.example.android.networkconnect.MainActivity.java
private int httptestconnect(String urlString) throws IOException { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true);//from w w w.j av a 2 s . c om conn.setRequestProperty("User-Agent", "e-venement-app/"); // Start the query conn.connect(); return conn.getResponseCode(); }