List of usage examples for java.net HttpURLConnection setUseCaches
public void setUseCaches(boolean usecaches)
From source file:com.laurencedawson.image_management.ImageManager.java
/** * Grab and save an image directly to disk * @param file The Bitmap file/*from w ww . j av a2 s. c o m*/ * @param url The URL of the image * @param imageCallback The callback associated with the request */ public static void cacheImage(final File file, ImageRequest imageCallback) { HttpURLConnection urlConnection = null; FileOutputStream fileOutputStream = null; InputStream inputStream = null; boolean isGif = false; try { // Setup the connection urlConnection = (HttpURLConnection) new URL(imageCallback.mUrl).openConnection(); urlConnection.setConnectTimeout(ImageManager.LONG_CONNECTION_TIMEOUT); urlConnection.setReadTimeout(ImageManager.LONG_REQUEST_TIMEOUT); urlConnection.setUseCaches(true); urlConnection.setInstanceFollowRedirects(true); // Set the progress to 0 imageCallback.sendProgressUpdate(imageCallback.mUrl, 0); // Connect inputStream = urlConnection.getInputStream(); // Do not proceed if the file wasn't downloaded if (urlConnection.getResponseCode() == 404) { urlConnection.disconnect(); return; } // Check if the image is a GIF String contentType = urlConnection.getHeaderField("Content-Type"); if (contentType != null) { isGif = contentType.equals(GIF_MIME); } // Grab the length of the image int length = 0; try { String fileLength = urlConnection.getHeaderField("Content-Length"); if (fileLength != null) { length = Integer.parseInt(fileLength); } } catch (NumberFormatException e) { if (ImageManager.DEBUG) { e.printStackTrace(); } } // Write the input stream to disk fileOutputStream = new FileOutputStream(file, true); int byteRead = 0; int totalRead = 0; final byte[] buffer = new byte[8192]; int frameCount = 0; // Download the image while ((byteRead = inputStream.read(buffer)) != -1) { // If the image is a gif, count the start of frames if (isGif) { for (int i = 0; i < byteRead - 3; i++) { if (buffer[i] == 33 && buffer[i + 1] == -7 && buffer[i + 2] == 4) { frameCount++; // Once we have at least one frame, stop the download if (frameCount > 1) { fileOutputStream.write(buffer, 0, i); fileOutputStream.close(); imageCallback.sendProgressUpdate(imageCallback.mUrl, 100); imageCallback.sendCachedCallback(imageCallback.mUrl, true); urlConnection.disconnect(); return; } } } } // Write the buffer to the file and update the total number of bytes // read so far (used for the callback) fileOutputStream.write(buffer, 0, byteRead); totalRead += byteRead; // Update the callback with the current progress if (length > 0) { imageCallback.sendProgressUpdate(imageCallback.mUrl, (int) (((float) totalRead / (float) length) * 100)); } } // Tidy up after the download if (fileOutputStream != null) { fileOutputStream.close(); } // Sent the callback that the image has been downloaded imageCallback.sendCachedCallback(imageCallback.mUrl, true); if (inputStream != null) { inputStream.close(); } // Disconnect the connection urlConnection.disconnect(); } catch (final MalformedURLException e) { if (ImageManager.DEBUG) { e.printStackTrace(); } // If the file exists and an error occurred, delete the file if (file != null) { file.delete(); } } catch (final IOException e) { if (ImageManager.DEBUG) { e.printStackTrace(); } // If the file exists and an error occurred, delete the file if (file != null) { file.delete(); } } }
From source file:com.scut.easyfe.network.kjFrame.http.HttpConnectStack.java
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int timeoutMs = request.getTimeoutMs(); connection.setConnectTimeout(timeoutMs); connection.setReadTimeout(timeoutMs); connection.setUseCaches(false); connection.setDoInput(true);//w ww. ja v a2 s.co m // use caller-provided custom SslSocketFactory, if any, for HTTPS if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) { ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory); } return connection; }
From source file:cn.garymb.wechatmoments.common.OkHttpStack.java
private HttpURLConnection openOkHttpURLConnection(OkUrlFactory factory, URL url, Request<?> request) throws IOException { HttpURLConnection connection = factory.open(url); int timeoutMs = request.getTimeoutMs(); connection.setConnectTimeout(timeoutMs); connection.setReadTimeout(timeoutMs); connection.setUseCaches(false); connection.setDoInput(true);/* w w w .j a v a 2 s .c om*/ // use caller-provided custom SslSocketFactory, if any, for HTTPS if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) { ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory); } return connection; }
From source file:net.sbbi.upnp.messages.StateVariableMessage.java
/** * Executes the state variable query and retuns the UPNP device response, according to the UPNP specs, * this method could take up to 30 secs to process ( time allowed for a device to respond to a request ) * @return a state variable response object containing the variable value * @throws IOException if some IOException occurs during message send and reception process * @throws UPNPResponseException if an UPNP error message is returned from the server * or if some parsing exception occurs ( detailErrorCode = 899, detailErrorDescription = SAXException message ) *///from w ww . jav a 2 s. co m public StateVariableResponse service() throws IOException, UPNPResponseException { StateVariableResponse rtrVal = null; UPNPResponseException upnpEx = null; IOException ioEx = null; StringBuffer body = new StringBuffer(256); body.append("<?xml version=\"1.0\"?>\r\n"); body.append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\""); body.append(" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"); body.append("<s:Body>"); body.append("<u:QueryStateVariable xmlns:u=\"urn:schemas-upnp-org:control-1-0\">"); body.append("<u:varName>").append(serviceStateVar.getName()).append("</u:varName>"); body.append("</u:QueryStateVariable>"); body.append("</s:Body>"); body.append("</s:Envelope>"); if (log.isDebugEnabled()) log.debug("POST prepared for URL " + service.getControlURL()); URL url = new URL(service.getControlURL().toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); HttpURLConnection.setFollowRedirects(false); //conn.setConnectTimeout( 30000 ); conn.setRequestProperty("HOST", url.getHost() + ":" + url.getPort()); conn.setRequestProperty("SOAPACTION", "\"urn:schemas-upnp-org:control-1-0#QueryStateVariable\""); conn.setRequestProperty("CONTENT-TYPE", "text/xml; charset=\"utf-8\""); conn.setRequestProperty("CONTENT-LENGTH", Integer.toString(body.length())); OutputStream out = conn.getOutputStream(); out.write(body.toString().getBytes()); out.flush(); conn.connect(); InputStream input = null; if (log.isDebugEnabled()) log.debug("executing query :\n" + body); try { input = conn.getInputStream(); } catch (IOException ex) { // java can throw an exception if he error code is 500 or 404 or something else than 200 // but the device sends 500 error message with content that is required // this content is accessible with the getErrorStream input = conn.getErrorStream(); } if (input != null) { int response = conn.getResponseCode(); String responseBody = getResponseBody(input); if (log.isDebugEnabled()) log.debug("received response :\n" + responseBody); SAXParserFactory saxParFact = SAXParserFactory.newInstance(); saxParFact.setValidating(false); saxParFact.setNamespaceAware(true); StateVariableResponseParser msgParser = new StateVariableResponseParser(serviceStateVar); StringReader stringReader = new StringReader(responseBody); InputSource src = new InputSource(stringReader); try { SAXParser parser = saxParFact.newSAXParser(); parser.parse(src, msgParser); } catch (ParserConfigurationException confEx) { // should never happen // we throw a runtimeException to notify the env problem throw new RuntimeException( "ParserConfigurationException during SAX parser creation, please check your env settings:" + confEx.getMessage()); } catch (SAXException saxEx) { // kind of tricky but better than nothing.. upnpEx = new UPNPResponseException(899, saxEx.getMessage()); } finally { try { input.close(); } catch (IOException ex) { // ignoring } } if (upnpEx == null) { if (response == HttpURLConnection.HTTP_OK) { rtrVal = msgParser.getStateVariableResponse(); } else if (response == HttpURLConnection.HTTP_INTERNAL_ERROR) { upnpEx = msgParser.getUPNPResponseException(); } else { ioEx = new IOException("Unexpected server HTTP response:" + response); } } } try { out.close(); } catch (IOException ex) { // ignore } conn.disconnect(); if (upnpEx != null) { throw upnpEx; } if (rtrVal == null && ioEx == null) { ioEx = new IOException("Unable to receive a response from the UPNP device"); } if (ioEx != null) { throw ioEx; } return rtrVal; }
From source file:org.hawkular.apm.client.api.rest.AbstractRESTClient.java
public HttpURLConnection getConnectionForRequest(String tenantId, URL url, String method) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); connection.setDoOutput(true);//from w w w . j av a 2s . com connection.setUseCaches(false); connection.setAllowUserInteraction(false); addHeaders(connection, tenantId); return connection; }
From source file:com.sun.socialsite.web.rest.servlets.ProxyServlet.java
/** * Handles the HTTP <code>POST</code> method. * @param req servlet request//w ww .j av a 2 s . c o m * @param resp servlet response */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { URL url = getURL(req, req.getParameter("uri")); HttpURLConnection con = (HttpURLConnection) (url.openConnection()); con.setDoOutput(true); con.setAllowUserInteraction(false); con.setUseCaches(false); // TODO: figure out why this is necessary for HTTPS URLs if (con instanceof HttpsURLConnection) { HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) { return true; } else { log.error("URL Host: " + urlHostName + " vs. " + session.getPeerHost()); return false; } } }; ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv); } // pass along all appropriate HTTP headers Enumeration headerNames = req.getHeaderNames(); while (headerNames.hasMoreElements()) { String hname = (String) headerNames.nextElement(); if (!unproxiedHeaders.contains(hname.toLowerCase())) { con.addRequestProperty(hname, req.getHeader(hname)); } } con.connect(); // read POST data from incoming request, write to outgoing request BufferedInputStream in = new BufferedInputStream(req.getInputStream()); BufferedOutputStream out = new BufferedOutputStream(con.getOutputStream()); byte buffer[] = new byte[8192]; for (int count = 0; count != -1;) { count = in.read(buffer, 0, 8192); if (count != -1) out.write(buffer, 0, count); } in.close(); out.close(); out.flush(); // read result headers of POST, write to response Map<String, List<String>> headers = con.getHeaderFields(); for (String key : headers.keySet()) { if (key != null) { // TODO: why is this check necessary! List<String> header = headers.get(key); if (header.size() > 0) resp.setHeader(key, header.get(0)); } } // read result data of POST, write out to response in = new BufferedInputStream(con.getInputStream()); out = new BufferedOutputStream(resp.getOutputStream()); for (int count = 0; count != -1;) { count = in.read(buffer, 0, 8192); if (count != -1) out.write(buffer, 0, count); } in.close(); out.close(); out.flush(); con.disconnect(); }
From source file:com.lark.http.LarkHurlStack.java
/** * Opens an {@link HttpURLConnection} with parameters. * @param url// w w w . j ava 2 s. c o m * @return an open connection * @throws IOException */ private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException { HttpURLConnection connection = createConnection(url); int timeoutMs = request.getTimeoutMs(); connection.setConnectTimeout(timeoutMs); connection.setReadTimeout(timeoutMs); connection.setUseCaches(false); connection.setDoInput(true); // use caller-provided custom SslSocketFactory, if any, for HTTPS if ("https".equals(url.getProtocol())) { HttpsTrustManager.allowAllSSL();//TODO really support? } return connection; }
From source file:com.lovebridge.library.volley.toolbox.HurlStack.java
/** * Opens an {@link HttpURLConnection} with parameters. * * @param url// w ww.j av a 2 s . c om * @return an open connection * @throws IOException */ private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException { HttpURLConnection connection = createConnection(url); int timeoutMs = request.getTimeoutMs(); connection.setConnectTimeout(timeoutMs); connection.setReadTimeout(timeoutMs); connection.setUseCaches(false); connection.setDoInput(true); // use caller-provided custom SslSocketFactory, if any, for HTTPS if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) { ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory); } return connection; }
From source file:org.bibsonomy.scraper.url.kde.blackwell.BlackwellSynergyScraper.java
/** FIXME: refactor * Extract the content of a scitation.aip.org page. * (changed code from ScrapingContext.getContentAsString) * @param urlConn Connection to api page (from url.openConnection()) * @param cookie Cookie for auth.//from ww w .j a v a 2s .c o m * @return Content of aip page. * @throws IOException */ private String getPageContent(HttpURLConnection urlConn, String cookie) throws IOException { urlConn.setAllowUserInteraction(true); urlConn.setDoInput(true); urlConn.setDoOutput(false); urlConn.setUseCaches(false); urlConn.setFollowRedirects(true); urlConn.setInstanceFollowRedirects(false); urlConn.setRequestProperty("Cookie", cookie); urlConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)"); urlConn.connect(); // build content StringWriter out = new StringWriter(); InputStream in = new BufferedInputStream(urlConn.getInputStream()); int b; while ((b = in.read()) >= 0) { out.write(b); } urlConn.disconnect(); in.close(); out.flush(); out.close(); return out.toString(); }
From source file:com.android.volley.util.HurlStack.java
/** * Opens an {@link HttpURLConnection} with parameters. * @param url/*from ww w.j a v a 2 s . c o m*/ * @return an open connection * @throws IOException */ private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int timeoutMs = request.getTimeoutMs(); connection.setConnectTimeout(timeoutMs); connection.setReadTimeout(timeoutMs); connection.setUseCaches(false); connection.setDoInput(true); // use caller-provided custom SslSocketFactory, if any, for HTTPS if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) { ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory); } return connection; }