List of usage examples for java.net HttpURLConnection getHeaderField
public String getHeaderField(int n)
From source file:com.gsoc.ijosa.liquidgalaxycontroller.PW.NearbyBeaconsFragment.java
private String getFileName(HttpURLConnection urlConnection) { try {//from ww w .jav a 2s. c om String fileName = ""; String raw = urlConnection.getHeaderField("Content-Disposition"); // raw = "attachment; filename=abc.jpg" if (raw != null && raw.contains("=")) { fileName = raw.split("=")[1]; //getting value after '=' fileName = fileName.split(";")[0]; } else { // fall back to random generated file name? } return fileName.replaceAll("\"", ""); } catch (Exception e) { e.printStackTrace(); return "unknowFileName"; } }
From source file:org.eclipse.rdf4j.http.server.ProtocolTest.java
/** * Checks that the requested content type is returned when accept header explicitly set. *//*from www . j a v a2s . co m*/ @Test public void testContentTypeForGraphQuery1_GET() throws Exception { String query = "DESCRIBE <foo:bar>"; String location = TestServer.REPOSITORY_URL; location += "?query=" + URLEncoder.encode(query, "UTF-8"); URL url = new URL(location); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Request RDF/XML formatted results: conn.setRequestProperty("Accept", RDFFormat.RDFXML.getDefaultMIMEType()); conn.connect(); try { int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { String contentType = conn.getHeaderField("Content-Type"); assertNotNull(contentType); // snip off optional charset declaration int charPos = contentType.indexOf(";"); if (charPos > -1) { contentType = contentType.substring(0, charPos); } assertEquals(RDFFormat.RDFXML.getDefaultMIMEType(), contentType); } else { String response = "location " + location + " responded: " + conn.getResponseMessage() + " (" + responseCode + ")"; fail(response); throw new RuntimeException(response); } } finally { conn.disconnect(); } }
From source file:uk.ac.ucl.excites.sapelli.collector.util.AsyncDownloader.java
private boolean download(String downloadUrl) { if (downloadUrl == null || downloadUrl.isEmpty()) { failure = new Exception("No URL given!"); return false; }/*from w w w. j av a 2 s. c o m*/ //Log.d(getClass().getSimpleName(), "Download URL: " + downloadUrl); if (DeviceControl.isOnline(context)) { InputStream input = null; OutputStream output = null; try { URL url = new URL(downloadUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setInstanceFollowRedirects(false); // we handle redirects manually below (otherwise HTTP->HTTPS redirects don't work): conn.connect(); // Detect & follow redirects: int status = conn.getResponseCode(); //Log.d(getClass().getSimpleName(), "Response Code: " + status); if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) { // follow redirect url from "location" header field String newUrl = conn.getHeaderField("Location"); //Log.d(getClass().getSimpleName(), "Redirect to URL : " + newUrl); return download(newUrl); } // Getting file length final int fileLength = conn.getContentLength(); publishProgress(fileLength < 0 ? // when fileLength = -1 this means the server hasn't specified the file length -1 : // progressDialog will open and be set to indeterminate mode 0); // progressDialog will open and be set to 0 // Input stream to read file - with 8k buffer input = new BufferedInputStream(url.openStream(), 8192); // Output stream to write file output = new BufferedOutputStream(new FileOutputStream(downloadedFile)); byte data[] = new byte[1024]; int total = 0; int percentage = 0; int bytesRead; while ((bytesRead = input.read(data)) != -1) { // Complete % completion: if (fileLength > 0) // don't divide by 0 and only update progress if we know the fileLength (i.e. != -1) { int newPercentage = (int) ((total += bytesRead) / ((float) fileLength) * 100f); if (newPercentage != percentage) publishProgress(percentage = newPercentage); } // Write data to file... output.write(data, 0, bytesRead); } // Flush output: output.flush(); } catch (Exception e) { failure = e; return false; } finally { // Close streams: StreamHelpers.SilentClose(input); StreamHelpers.SilentClose(output); } //Log.d(getClass().getSimpleName(), "Download done"); return true; } else { failure = new Exception("The device is not online."); return false; } }
From source file:org.jboss.aerogear.unifiedpush.SenderClient.java
/** * The actual method that does the real send and connection handling * //from w w w . j ava 2s . c om * @param url the URL to use for the HTTP POST request. * @param jsonPayloadObject the JSON payload of the POST request * @param pushApplicationId the registered applications identifier. * @param masterSecret the master secret for the push server. * @param callback the {@link MessageResponseCallback} that will be called once the POST request completes. */ private void submitPayload(String url, String jsonPayloadObject, String pushApplicationId, String masterSecret, MessageResponseCallback callback) { String credentials = pushApplicationId + ':' + masterSecret; int statusCode; HttpURLConnection httpURLConnection = null; try { String encoded = Base64.encodeBytes(credentials.getBytes(UTF_8)); // POST the payload to the UnifiedPush Server httpURLConnection = (HttpURLConnection) HttpClient.post(url, encoded, jsonPayloadObject, UTF_8, proxy, customTrustStore); statusCode = httpURLConnection.getResponseCode(); logger.info(String.format("HTTP Response code from UnifiedPush Server: %s", statusCode)); // if we got a redirect, let's extract the 'Location' header from the response // and submit the payload again if (isRedirect(statusCode)) { String redirectURL = httpURLConnection.getHeaderField("Location"); logger.info(String.format("Performing redirect to '%s'", redirectURL)); // execute the 'redirect' submitPayload(redirectURL, jsonPayloadObject, pushApplicationId, masterSecret, callback); } else { if (callback != null) { callback.onComplete(statusCode); } } } catch (Exception e) { logger.severe("Send did not succeed: " + e.getMessage()); if (callback != null) { callback.onError(e); } } finally { // tear down if (httpURLConnection != null) { httpURLConnection.disconnect(); } } }
From source file:org.openestate.is24.restapi.DefaultClient.java
/** * Retrieve a {@link Response} from a request, that was sent through * {@link HttpURLConnection}./*from w w w . j a v a2s .c o m*/ * * @param connection * {@link HttpURLConnection}, that contains the server response * * @return * {@link Response} of the request * * @throws IOException * if the {@link Response} can't be obtained */ protected Response createResponse(HttpURLConnection connection) throws IOException { InputStream responseInput = null; try { //String encoding = StringUtils.trimToNull( connection.getContentEncoding() ); //if (encoding==null) encoding = getEncoding(); String encoding = getEncoding(); // read response body responseInput = new BufferedInputStream(connection.getInputStream()); // possibly decompress response body from gzip if ("gzip".equalsIgnoreCase(connection.getContentEncoding())) responseInput = new GZIPInputStream(responseInput); // create response return new Response(connection.getResponseCode(), connection.getResponseMessage(), connection.getHeaderField(RESPONSE_HEADER_REQUEST_REFNUM), IOUtils.toString(responseInput, encoding)); } finally { IOUtils.closeQuietly(responseInput); IOUtils.close(connection); } }
From source file:org.eclipse.rdf4j.http.server.ProtocolTest.java
@Test public void testQueryResponse_HEAD() throws Exception { String query = "DESCRIBE <foo:bar>"; String location = TestServer.REPOSITORY_URL; location += "?query=" + URLEncoder.encode(query, "UTF-8"); URL url = new URL(location); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); // Request RDF/XML formatted results: conn.setRequestProperty("Accept", RDFFormat.RDFXML.getDefaultMIMEType()); conn.connect();/*from w w w . ja va 2 s . c o m*/ try { int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { String contentType = conn.getHeaderField("Content-Type"); assertNotNull(contentType); // snip off optional charset declaration int charPos = contentType.indexOf(";"); if (charPos > -1) { contentType = contentType.substring(0, charPos); } assertEquals(RDFFormat.RDFXML.getDefaultMIMEType(), contentType); assertEquals(0, conn.getContentLength()); } else { String response = "location " + location + " responded: " + conn.getResponseMessage() + " (" + responseCode + ")"; fail(response); throw new RuntimeException(response); } } finally { conn.disconnect(); } }
From source file:at.spardat.xma.boot.transport.HTTPTransport.java
/** * Parses the cookies from the given connection and stores them in httpState. * Invalid cookies are ignored and logged. *///from w w w .j ava2s . c om private void readCookies(IRtXMASessionClient session, URL url, HttpURLConnection conn) { String headerName = ""; for (int i = 1; headerName != null; i++) { headerName = conn.getHeaderFieldKey(i); if (Statics.HTTP_SET_COOKIE.equals(headerName)) { try { Cookie[] cookies = cookieSpec.parse(url.getHost(), getPort(url), url.getPath(), "https".equals(url.getProtocol()), conn.getHeaderField(i)); if (cookies != null) { for (int j = 0; j < cookies.length; j++) { try { cookieSpec.validate(url.getHost(), getPort(url), url.getPath(), "https".equals(url.getProtocol()), cookies[j]); getHttpState(session).addCookie(cookies[j]); if (session != null && "JSESSIONID".equals(cookies[j].getName())) { session.setId(cookies[j].getName() + "=" + cookies[j].getValue()); } } catch (MalformedCookieException e) { log_.log(LogLevel.WARNING, "cookie rejected: \"" + cookieSpec.formatCookie(cookies[j]) + "\". " + e.getMessage()); } } } } catch (MalformedCookieException e) { log_.log(LogLevel.WARNING, "Invalid cookie header: \"" + conn.getHeaderField(i) + "\". " + e.getMessage()); } } } }
From source file:fi.cosky.sdk.API.java
private String readDataFromConnection(HttpURLConnection connection) { InputStream is = null;/*from ww w . j av a 2 s. c o m*/ BufferedReader br = null; StringBuilder sb = null; try { is = connection.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } String eTag = null; if ((eTag = connection.getHeaderField("ETag")) != null) { sb.insert(sb.lastIndexOf("}"), ",\"VersionNumber\":" + eTag + ""); } } catch (IOException e) { System.out.println("Could not read data from connection"); } return sb.toString(); }
From source file:com.google.ytd.picasa.PicasaApiHelper.java
public PhotoEntry doResumableUpload(com.google.ytd.model.PhotoEntry photoEntry) throws IllegalArgumentException { if (util.isNullOrEmpty(photoEntry.getResumableUploadUrl())) { throw new IllegalArgumentException(String .format("No resumable upload URL found for " + "PhotoEntry id '%s'.", photoEntry.getId())); }//from ww w .j a va 2 s .co m try { URL url = new URL(photoEntry.getResumableUploadUrl()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); connection.setRequestMethod("PUT"); connection.setRequestProperty("Content-Range", "bytes */*"); // Response code 308 is specific to this use case and doesn't appear to have a // HttpURLConnection constant. if (connection.getResponseCode() == 308) { long previousByte = 0; String rangeHeader = connection.getHeaderField("Range"); if (!util.isNullOrEmpty(rangeHeader)) { LOG.info("Range header in 308 response is " + rangeHeader); String[] rangeHeaderSplits = rangeHeader.split("-", 2); if (rangeHeaderSplits.length == 2) { previousByte = Long.valueOf(rangeHeaderSplits[1]).longValue() + 1; } } connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); connection.setRequestMethod("PUT"); byte[] bytes; String contentRangeHeader; if (photoEntry.getBlobKey() != null) { long lastByte = previousByte + CHUNK_SIZE; if (lastByte > (photoEntry.getOriginalFileSize() - 1)) { lastByte = photoEntry.getOriginalFileSize() - 1; } contentRangeHeader = String.format("bytes %d-%d/%d", previousByte, lastByte, photoEntry.getOriginalFileSize()); BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService(); bytes = blobstoreService.fetchData(photoEntry.getBlobKey(), previousByte, lastByte); } else { bytes = dataChunkDao.getBytes(photoEntry.getId(), previousByte); if (bytes == null) { throw new IllegalArgumentException(String.format("PhotoEntry with id '%s' does not " + "have a valid blob key. Additionally, there is no DataChunk entry for the " + "initial byte '%d'.", photoEntry.getId(), previousByte)); } contentRangeHeader = String.format("bytes %d-%d/%d", previousByte, previousByte + bytes.length - 1, photoEntry.getOriginalFileSize()); } connection.setRequestProperty("Content-Length", String.valueOf(bytes.length)); LOG.info("Using the following for Content-Range header: " + contentRangeHeader); connection.setRequestProperty("Content-Range", contentRangeHeader); OutputStream outputStream = connection.getOutputStream(); outputStream.write(bytes); outputStream.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) { LOG.info("Resumable upload is complete and successful."); return (PhotoEntry) ParseUtil.readEntry(new ParseSource(connection.getInputStream())); } } else if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) { // It's possible that the Picasa upload associated with the specific resumable upload URL // had previously completed successfully. In that case, the response to the initial */* PUT // will be a 201 Created with the new PhotoEntry. This is probably an edge case. LOG.info("Resumable upload is complete and successful."); return (PhotoEntry) ParseUtil.readEntry(new ParseSource(connection.getInputStream())); } else { // The IllegalArgumentException should be treated by the calling code as // something that is not recoverable, which is to say the resumable upload attempt // should be stopped. throw new IllegalArgumentException(String.format("HTTP POST to %s returned status %d (%s).", url.toString(), connection.getResponseCode(), connection.getResponseMessage())); } } catch (MalformedURLException e) { LOG.log(Level.WARNING, "", e); throw new IllegalArgumentException(e); } catch (IOException e) { LOG.log(Level.WARNING, "", e); } catch (ServiceException e) { LOG.log(Level.WARNING, "", e); } return null; }