List of usage examples for java.net HttpURLConnection setInstanceFollowRedirects
public void setInstanceFollowRedirects(boolean followRedirects)
From source file:org.dataconservancy.dcs.util.droid.DroidSignatureFileManager.java
/** * Checks if the url of the of the file exists and then downloads it to the provided file if it does. * @param fileUrl The url of the file to retrieve. * @param signatureFile The file object that should be used to store the contents of the file at the url. * @return True if the url was found and the contents were able to be stored in the file, false otherwise. *///from w w w . ja va2 s .c o m private boolean downloadLatestFile(URL fileUrl, File signatureFile) { boolean fileRetrieved = true; log.info("Attempting to download droid file: " + fileUrl); String contentType = ""; try { HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection(); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("GET"); connection.connect(); contentType = connection.getHeaderField("Content-Type"); } catch (IOException e) { fileRetrieved = false; log.error("Error connection to file url: " + fileUrl + " Exception: " + e.getMessage()); } if (fileRetrieved) { //National Archives website returns 200 even if the url doesn't exist, so check to make sure the content type is xml and not html if (contentType.equalsIgnoreCase("text/xml")) { try { FileUtils.copyURLToFile(fileUrl, signatureFile); } catch (IOException e) { fileRetrieved = false; log.error("Error connection to file url: " + fileUrl + " Exception: " + e.getMessage()); } log.info("Successfully downloaded droid file: " + fileUrl); } else { fileRetrieved = false; } } return fileRetrieved; }
From source file:com.baasbox.android.HttpUrlConnectionClient.java
private HttpURLConnection openConnection(String urlString) throws BaasIOException, IOException { URL url = null;/*from w w w. jav a2 s . c o m*/ try { url = new URL(urlString); } catch (MalformedURLException e) { throw new BaasIOException("Error while parsing url " + urlString, e); } HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(config.httpConnectionTimeout); connection.setReadTimeout(config.httpSocketTimeout); connection.setInstanceFollowRedirects(true); connection.setDoInput(true); return connection; }
From source file:com.wisc.cs407project.ImageLoader.ImageLoader.java
private Bitmap getBitmap(String url) { File f = fileCache.getFile(url); Bitmap b = decodeFile(f);/*www . j a v a 2 s .com*/ //from Local Directory BufferedReader in = null; UrlValidator validator = new UrlValidator(); if (new File(url).exists()) { b = decodeFile(new File(url)); if (b != null) return b; } //from web try { //check SD cache first if (b != null) return b; Bitmap bitmap = null; URL imageUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setInstanceFollowRedirects(true); InputStream is = conn.getInputStream(); OutputStream os = new FileOutputStream(f); Utils.CopyStream(is, os); os.close(); conn.disconnect(); bitmap = decodeFile(f); return bitmap; } catch (Throwable ex) { ex.printStackTrace(); if (ex instanceof OutOfMemoryError) memoryCache.clear(); return null; } }
From source file:technology.tikal.accounts.dao.rest.SessionDaoRest.java
private void guardar(UserSession objeto, int intento) { //basic auth string String basicAuthString = config.getUser() + ":" + config.getPassword(); basicAuthString = new String(Base64.encodeBase64(basicAuthString.getBytes())); basicAuthString = "Basic " + basicAuthString; //mensaje remoto try {/* w w w . j a v a 2s .co m*/ //config URL url = new URL(config.getUrl()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod(config.getMethod()); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Authorization", basicAuthString); connection.setInstanceFollowRedirects(false); //write OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(mapper.writeValueAsString(objeto)); //close writer.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) { return; } else { throw new MessageSourceResolvableException(new DefaultMessageSourceResolvable( new String[] { "SessionCreationRefused.SessionDaoRest.guardar" }, new String[] { connection.getResponseCode() + "" }, "")); } } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { if (intento <= maxRetry) { this.guardar(objeto, intento + 1); } else { throw new MessageSourceResolvableException(new DefaultMessageSourceResolvable( new String[] { "SessionCreationError.SessionDaoRest.guardar" }, new String[] { e.getMessage() }, "")); } } }
From source file:com.commsen.jwebthumb.WebThumbService.java
/** * Helper method used to actually send {@link WebThumb} request and check for common errors. * //from w w w . j a v a 2 s . c o m * @param webThumb the request to send * @return connection to extract the response from * @throws WebThumbException if any error occurs */ private HttpURLConnection sendWebThumb(WebThumb webThumb) throws WebThumbException { try { HttpURLConnection connection = (HttpURLConnection) new URL(WEB_THUMB_URL).openConnection(); connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setRequestMethod("POST"); SimpleXmlSerializer.generateRequest(webThumb, connection.getOutputStream()); int responseCode = connection.getResponseCode(); String contentType = getContentType(connection); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Request sent! Got response: " + responseCode + " " + connection.getResponseMessage()); LOGGER.fine("Response content type: " + contentType); LOGGER.fine("Response content encoding: " + connection.getContentEncoding()); LOGGER.fine("Response content length: " + connection.getContentLength()); } if (responseCode == HttpURLConnection.HTTP_OK) { if (CONTENT_TYPE_TEXT_PLAIN.equals(contentType)) { throw new WebThumbException( "Server side error: " + IOUtils.toString(connection.getInputStream())); } if (!CONTENT_TYPE_TEXT_XML.equals(contentType)) { throw new WebThumbException("Unknown content type in response: " + contentType); } return connection; } else { throw new WebThumbException("Server side error: " + connection.getResponseCode() + ") " + connection.getResponseMessage()); } } catch (MalformedURLException e) { throw new WebThumbException("failed to send request", e); } catch (IOException e) { throw new WebThumbException("failed to send request", e); } }
From source file:org.callimachusproject.test.WebResource.java
public int headCode() throws IOException { HttpURLConnection con = (HttpURLConnection) new URL(uri).openConnection(); con.setInstanceFollowRedirects(false); con.setRequestMethod("HEAD"); return con.getResponseCode(); }
From source file:gov.whitehouse.services.LiveService.java
private boolean updateEvents() { try {//from ww w.j a va 2 s. com HttpURLConnection conn = (HttpURLConnection) new URL(mFeedUrl).openConnection(); InputStream in; int status; conn.setDoInput(true); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("User-Agent", getString(R.string.user_agent_string)); in = conn.getInputStream(); status = conn.getResponseCode(); if (status < 400 && status != 304) { /* We should be good to go */ SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); FeedHandler handler = new FeedHandler(); parser.parse(in, handler); /* * Cycle through the received events and make sure they're all valid. */ ArrayList<FeedItem> validLiveEvents = new ArrayList<FeedItem>(); for (FeedItem item : handler.getFeedItems()) { if (item != null && item.getPubDate() != null) { validLiveEvents.add(item); } } mLiveEvents = validLiveEvents; } conn.disconnect(); return status < 400; } catch (SAXException e) { Log.d(TAG, "failed to parse XML"); Log.d(TAG, Log.getStackTraceString(e)); } catch (IOException e) { Log.d(TAG, "error reading feed"); Log.d(TAG, Log.getStackTraceString(e)); } catch (IllegalStateException e) { Log.d(TAG, "this should not happen"); Log.d(TAG, Log.getStackTraceString(e)); } catch (ParserConfigurationException e) { Log.d(TAG, "this should not happen"); Log.d(TAG, Log.getStackTraceString(e)); } return false; }
From source file:org.callimachusproject.test.WebResource.java
public String getRedirectLocation() throws IOException { HttpURLConnection con = (HttpURLConnection) new URL(uri).openConnection(); con.setInstanceFollowRedirects(false); con.setRequestMethod("HEAD"); int code = con.getResponseCode(); if (!(code == 301 || code == 303 || code == 302 || code == 307 || code == 308)) Assert.assertEquals(con.getResponseMessage(), 302, code); return con.getHeaderField("Location"); }
From source file:zoho.ZohoService.java
/** * Add a new log// ww w.ja va 2s . com * @param token User token * @param url url of the log * @param note Notes * @param date Date * @param bill Bill status * @param hour Total hour * @return response code or -1 if error */ public int addLog(String token, String url, String note, String date, String bill, String hour) { int res = -1; try { String urlParam = "date=" + date + "&bill_status=" + bill + "&hours=" + hour; urlParam += "¬es=" + note + "&authtoken=" + token; byte[] postData = urlParam.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setDoOutput(true); con.setInstanceFollowRedirects(false); con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", "Mozilla/40.0"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("charset", "utf-8"); con.setRequestProperty("Content-Length", Integer.toString(postDataLength)); con.setUseCaches(false); try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) { wr.write(postData); } int responseCode = con.getResponseCode(); System.out.println("Response code " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); res = responseCode; } catch (MalformedURLException ex) { Logger.getLogger(ZohoService.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ZohoService.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception e) { System.out.println("Some error occured... Please come back later.. :("); } return res; }
From source file:com.commsen.jwebthumb.WebThumbService.java
private HttpURLConnection getFetchConnection(WebThumbFetchRequest webThumbFetchRequest) throws WebThumbException { Validate.notNull(webThumbFetchRequest, "webThumbFetchRequest is null!"); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Attempting to send webThumbFetchRequest: " + webThumbFetchRequest); }/* w ww . ja v a 2 s . c om*/ WebThumb webThumb = new WebThumb(apikey, webThumbFetchRequest); try { HttpURLConnection connection = (HttpURLConnection) new URL(WEB_THUMB_URL).openConnection(); connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setRequestMethod("POST"); SimpleXmlSerializer.generateRequest(webThumb, connection.getOutputStream()); int responseCode = connection.getResponseCode(); String contentType = getContentType(connection); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("webThumbFetchRequest sent. Got response: " + responseCode + " " + connection.getResponseMessage()); LOGGER.fine("Content type: " + contentType); } if (responseCode == HttpURLConnection.HTTP_OK) { if (CONTENT_TYPE_TEXT_PLAIN.equals(contentType)) { throw new WebThumbException( "Server side error: " + IOUtils.toString(connection.getInputStream())); } return connection; } else if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) { WebThumbResponse webThumbResponse = SimpleXmlSerializer.parseResponse(connection.getErrorStream(), WebThumbResponse.class); throw new WebThumbException("Server side error: " + webThumbResponse.getError().getValue()); } else { throw new WebThumbException("Server side error: " + connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (MalformedURLException e) { throw new WebThumbException("failed to send request", e); } catch (IOException e) { throw new WebThumbException("failed to send request", e); } }