List of usage examples for java.net HttpURLConnection setUseCaches
public void setUseCaches(boolean usecaches)
From source file:com.mendhak.gpslogger.senders.gdocs.GDocsHelper.java
private String UpdateFileContents(String authToken, String gpxFileId, byte[] fileContents) { HttpURLConnection conn = null; String fileId = null;//from w w w. j a v a 2 s . c o m String fileUpdateUrl = "https://www.googleapis.com/upload/drive/v2/files/" + gpxFileId + "?uploadType=media"; try { if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) { //Due to a pre-froyo bug //http://android-developers.blogspot.com/2011/09/androids-http-clients.html System.setProperty("http.keepAlive", "false"); } URL url = new URL(fileUpdateUrl); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); conn.setRequestProperty("User-Agent", "GPSLogger for Android"); conn.setRequestProperty("Authorization", "Bearer " + authToken); conn.setRequestProperty("Content-Type", "application/xml"); conn.setRequestProperty("Content-Length", String.valueOf(fileContents.length)); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.write(fileContents); wr.flush(); wr.close(); String fileMetadata = Utilities.GetStringFromInputStream(conn.getInputStream()); JSONObject fileMetadataJson = new JSONObject(fileMetadata); fileId = fileMetadataJson.getString("id"); Utilities.LogDebug("File updated : " + fileId); } catch (Exception e) { System.out.println(e.getMessage()); } finally { if (conn != null) { conn.disconnect(); } } return fileId; }
From source file:com.geotrackin.gpslogger.senders.gdocs.GDocsHelper.java
private String UpdateFileContents(String authToken, String gpxFileId, byte[] fileContents, String fileName) { HttpURLConnection conn = null; String fileId = null;//from w ww . j a v a 2s .co m String fileUpdateUrl = "https://www.googleapis.com/upload/drive/v2/files/" + gpxFileId + "?uploadType=media"; try { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { //Due to a pre-froyo bug //http://android-developers.blogspot.com/2011/09/androids-http-clients.html System.setProperty("http.keepAlive", "false"); } URL url = new URL(fileUpdateUrl); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); conn.setRequestProperty("User-Agent", "GPSLogger for Android"); conn.setRequestProperty("Authorization", "Bearer " + authToken); conn.setRequestProperty("Content-Type", GetMimeTypeFromFileName(fileName)); conn.setRequestProperty("Content-Length", String.valueOf(fileContents.length)); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.write(fileContents); wr.flush(); wr.close(); String fileMetadata = Utilities.GetStringFromInputStream(conn.getInputStream()); JSONObject fileMetadataJson = new JSONObject(fileMetadata); fileId = fileMetadataJson.getString("id"); tracer.debug("File updated : " + fileId); } catch (Exception e) { System.out.println(e.getMessage()); } finally { if (conn != null) { conn.disconnect(); } } return fileId; }
From source file:com.hollandhaptics.babyapp.BabyService.java
/** * @param sourceFile The file to upload. * @return int The server's response code. * @brief Uploads a file to the server. Is called by uploadAudioFiles(). *//*from w w w . j av a 2s .c om*/ public int uploadFile(File sourceFile) { HttpURLConnection conn; DataOutputStream dos; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1024 * 1024; String sourceFileUri = sourceFile.getAbsolutePath(); if (!sourceFile.isFile()) { Log.e("uploadFile", "Source File does not exist :" + sourceFileUri); return 0; } else { try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); // Open a HTTP connection to the URL conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("fileToUpload", sourceFileUri); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"fileToUpload\";filename=\"" + sourceFileUri + "\"" + lineEnd); dos.writeBytes(lineEnd); // create a buffer of maximum size bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 200) { boolean deleted = sourceFile.delete(); Log.i("Deleted succes", String.valueOf(deleted)); } //close the streams // fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); Log.e("Upload file to server", "error: " + ex.getMessage(), ex); } catch (Exception e) { e.printStackTrace(); Log.e("Upload file to server", "Exception : " + e.getMessage(), e); } return serverResponseCode; } // End else block }
From source file:it.acubelab.smaph.SmaphAnnotator.java
/** * Issue the query to bing, return the json object. * // w w w.java2s.c o m * @param query * the query. * @param retryLeft * how many retry left we have (if zero, will return an empty * object in case of failure). * @return the JSON object as returned by the Bing Api. * @throws Exception * is the call to the API failed. */ private synchronized JSONObject queryBing(String query, int retryLeft) throws Exception { boolean forceCacheOverride = retryLeft < BING_RETRY; if (forceCacheOverride) Thread.sleep(1000); String accountKeyAuth = Base64.encode((bingKey + ":" + bingKey).getBytes(), 0); URL url = new URL( "https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27web%2Bspell%2BRelatedSearch%27&Query=%27" + URLEncoder.encode(query, "utf8") + "%27&Options=%27EnableHighlighting%27&Market=%27en-US%27&Adult=%27Off%27&$format=Json"); JSONObject result = null; byte[] compressed = url2jsonCache.get(url.toExternalForm()); if (compressed != null) result = new JSONObject(SmaphUtils.decompress(compressed)); boolean cached = !forceCacheOverride && result != null; SmaphAnnotatorDebugger.out.printf("%s%s %s%n", forceCacheOverride ? "<forceCacheOverride>" : "", cached ? "<cached>" : "Querying", url); if (!cached) { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(0); connection.setRequestProperty("Authorization", "Basic " + accountKeyAuth); connection.setRequestProperty("Accept", "*/*"); connection.setRequestProperty("Content-Type", "multipart/form-data"); connection.setUseCaches(false); if (connection.getResponseCode() != 200) { Scanner s = new Scanner(connection.getErrorStream()).useDelimiter("\\A"); System.err.printf("Got HTTP error %d. Message is: %s%n", connection.getResponseCode(), s.next()); s.close(); throw new RuntimeException("Got response code:" + connection.getResponseCode()); } Scanner s = new Scanner(connection.getInputStream()).useDelimiter("\\A"); String resultStr = s.hasNext() ? s.next() : ""; result = new JSONObject(resultStr); url2jsonCache.put(url.toExternalForm(), SmaphUtils.compress(result.toString())); increaseFlushCounter(); } if (recacheNeeded(result) && retryLeft > 0) return queryBing(query, retryLeft - 1); return result; }
From source file:org.dcm4che3.tool.stowrs.StowRS.java
private StowRSResponse sendMetaDataAndBulkData(Attributes metadata, ExtractedBulkData extractedBulkData) throws IOException { Attributes responseAttrs = new Attributes(); URL newUrl;/*from www .j a v a 2s . c o m*/ try { newUrl = new URL(URL); } catch (MalformedURLException e2) { throw new RuntimeException(e2); } HttpURLConnection connection = (HttpURLConnection) newUrl.openConnection(); connection.setChunkedStreamingMode(2048); connection.setDoOutput(true); connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("POST"); String metaDataType = mediaType == StowMetaDataType.XML ? "application/dicom+xml" : "application/json"; connection.setRequestProperty("Content-Type", "multipart/related; type=" + metaDataType + "; boundary=" + MULTIPART_BOUNDARY); String bulkDataTransferSyntax = "transfer-syntax=" + transferSyntax; MediaType pixelDataMediaType = getBulkDataMediaType(metadata); connection.setRequestProperty("Accept", "application/dicom+xml"); connection.setRequestProperty("charset", "utf-8"); connection.setUseCaches(false); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); // write metadata wr.writeBytes("\r\n--" + MULTIPART_BOUNDARY + "\r\n"); if (mediaType == StowMetaDataType.XML) wr.writeBytes("Content-Type: application/dicom+xml; " + bulkDataTransferSyntax + " \r\n"); else wr.writeBytes("Content-Type: application/json; " + bulkDataTransferSyntax + " \r\n"); wr.writeBytes("\r\n"); coerceAttributes(metadata, keys); try { if (mediaType == StowMetaDataType.XML) SAXTransformer.getSAXWriter(new StreamResult(wr)).write(metadata); else { JsonGenerator gen = Json.createGenerator(wr); JSONWriter writer = new JSONWriter(gen); writer.write(metadata); gen.flush(); } } catch (TransformerConfigurationException e) { throw new IOException(e); } catch (SAXException e) { throw new IOException(e); } // write bulkdata for (BulkData chunk : extractedBulkData.otherBulkDataChunks) { writeBulkDataPart(MediaType.APPLICATION_OCTET_STREAM_TYPE, wr, chunk.getURIOrUUID(), Collections.singletonList(chunk)); } if (!extractedBulkData.pixelDataBulkData.isEmpty()) { // pixeldata as a single bulk data part if (extractedBulkData.pixelDataBulkData.size() > 1) { LOG.info("Combining bulk data of multiple pixel data fragments"); } writeBulkDataPart(pixelDataMediaType, wr, extractedBulkData.pixelDataBulkDataURI, extractedBulkData.pixelDataBulkData); } // end of multipart message wr.writeBytes("\r\n--" + MULTIPART_BOUNDARY + "--\r\n"); wr.close(); String response = connection.getResponseMessage(); int rspCode = connection.getResponseCode(); LOG.info("response: " + response); try { responseAttrs = SAXReader.parse(connection.getInputStream()); } catch (Exception e) { LOG.error("Error creating response attributes", e); } connection.disconnect(); return new StowRSResponse(rspCode, response, responseAttrs); }
From source file:org.apache.openaz.xacml.rest.XACMLPdpRegisterThread.java
/** * This is our thread that runs on startup to tell the PAP server we are up-and-running. *//*w w w .ja v a 2s. com*/ @Override public void run() { synchronized (this) { this.isRunning = true; } boolean registered = false; boolean interrupted = false; int seconds; try { seconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_SLEEP)); } catch (NumberFormatException e) { logger.error("REGISTER_SLEEP: ", e); seconds = 5; } if (seconds < 5) { seconds = 5; } int retries; try { retries = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_RETRIES)); } catch (NumberFormatException e) { logger.error("REGISTER_SLEEP: ", e); retries = -1; } while (!registered && !interrupted && this.isRunning()) { HttpURLConnection connection = null; try { // // Get the PAP Servlet URL // URL url = new URL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL)); logger.info("Registering with " + url.toString()); boolean finished = false; while (!finished) { // // Open up the connection // connection = (HttpURLConnection) url.openConnection(); // // Setup our method and headers // connection.setRequestMethod("POST"); connection.setRequestProperty("Accept", "text/x-java-properties"); connection.setRequestProperty("Content-Type", "text/x-java-properties"); connection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID, XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID)); connection.setUseCaches(false); // // Adding this in. It seems the HttpUrlConnection class does NOT // properly forward our headers for POST re-direction. It does so // for a GET re-direction. // // So we need to handle this ourselves. // connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setDoInput(true); try { // // Send our current policy configuration // String lists = XACMLProperties.PROP_ROOTPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES); lists = lists + "\n" + XACMLProperties.PROP_REFERENCEDPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES) + "\n"; try (InputStream listsInputStream = new ByteArrayInputStream(lists.getBytes()); InputStream pipInputStream = Files.newInputStream(XACMLPdpLoader.getPIPConfig()); OutputStream os = connection.getOutputStream()) { IOUtils.copy(listsInputStream, os); // // Send our current PIP configuration // IOUtils.copy(pipInputStream, os); } } catch (Exception e) { logger.error("Failed to send property file", e); } // // Do the connect // connection.connect(); if (connection.getResponseCode() == 204) { logger.info("Success. We are configured correctly."); finished = true; registered = true; } else if (connection.getResponseCode() == 200) { logger.info("Success. We have a new configuration."); Properties properties = new Properties(); properties.load(connection.getInputStream()); logger.info("New properties: " + properties.toString()); // // Queue it // // The incoming properties does NOT include urls PutRequest req = new PutRequest(XACMLProperties.getPolicyProperties(properties, false), XACMLProperties.getPipProperties(properties)); XACMLPdpServlet.queue.offer(req); // // We are now registered // finished = true; registered = true; } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) { // // Re-direction // String newLocation = connection.getHeaderField("Location"); if (newLocation == null || newLocation.isEmpty()) { logger.warn("Did not receive a valid re-direction location"); finished = true; } else { logger.info("New Location: " + newLocation); url = new URL(newLocation); } } else { logger.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); finished = true; } } } catch (Exception e) { logger.error(e); } finally { // cleanup the connection if (connection != null) { try { // For some reason trying to get the inputStream from the connection // throws an exception rather than returning null when the InputStream does not exist. InputStream is = null; try { is = connection.getInputStream(); } catch (Exception e1) { //NOPMD // ignore this } if (is != null) { is.close(); } } catch (IOException ex) { logger.error("Failed to close connection: " + ex, ex); } connection.disconnect(); } } // // Wait a little while to try again // try { if (!registered) { if (retries > 0) { retries--; } else if (retries == 0) { break; } Thread.sleep(seconds * 1000); } } catch (InterruptedException e) { interrupted = true; this.terminate(); } } synchronized (this) { this.isRunning = false; } logger.info("Thread exiting...(registered=" + registered + ", interrupted=" + interrupted + ", isRunning=" + this.isRunning() + ", retries=" + retries + ")"); }
From source file:by.belisa.util.OnlineConvert.java
/** * apiCall Make an API call to server based on action and parameters. * * @param action API action name//from w w w . ja v a 2 s . c om * @param query List Object of xml data * @param formatOptionXml xml string for extra format options * @return xml response string from server. */ private String apiCall(String action, List query, String formatOptionXml) { String currentUrl = OnlineConvert.URL; String xmlResponse = ""; /*if (!"get-queue".equals(action)) { this.getServer(this.targetTypeOptions.get(this.targetType)); }*/ try { URL browser = new URL(currentUrl + "/" + action); HttpURLConnection conn = (HttpURLConnection) browser.openConnection(); String params = "queue=" + URLEncoder.encode( this.getMap2XML((Map) query.get(OnlineConvert.QUEUE_COMMAN_PARAMS), "<?xml version=\"1.0\" encoding=\"UTF-8\"?>", formatOptionXml + this .getFileMap2XML((Map) query.get(OnlineConvert.QUEUE_FILE_METADATA_PARAMS))), "UTF-8"); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(params.length())); conn.setUseCaches(false); conn.setDoOutput(true); conn.setDoInput(true); OutputStream wr = conn.getOutputStream(); wr.write(params.getBytes()); wr.flush(); // Get the response BufferedReader in; in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } xmlResponse = response.toString(); wr.close(); in.close(); } catch (IOException e) { } return xmlResponse; }
From source file:com.etalio.android.EtalioBase.java
protected String multipartRequest(String urlTo, InputStream fileInputStream, String filefield, String filename) throws ParseException, IOException, EtalioHttpException { HttpURLConnection connection = null; DataOutputStream outputStream = null; InputStream inputStream = null; String twoHyphens = "--"; String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****"; String lineEnd = "\r\n"; String result = ""; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; try {/* www . j a v a 2 s . c om*/ URL url = new URL(urlTo); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Authorization", " Bearer " + getEtalioToken().getAccessToken()); connection.setRequestProperty("User-Agent", getEtalioUserAgent()); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + filename + "\"" + lineEnd); outputStream.writeBytes("Content-Type: " + MimeTypeUtil.getMimeType(filename) + lineEnd); outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { outputStream.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } outputStream.writeBytes(lineEnd); outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); inputStream = connection.getInputStream(); if (connection.getResponseCode() > 300) { result = convertStreamToString(connection.getErrorStream()); } else { result = this.convertStreamToString(inputStream); } fileInputStream.close(); inputStream.close(); outputStream.flush(); outputStream.close(); return result; } catch (Exception e) { throw new EtalioHttpException(connection.getResponseCode(), connection.getResponseMessage(), e.getMessage()); } }
From source file:org.apache.openaz.xacml.pdp.test.TestBase.java
/** * This makes an HTTP POST call to a running PDP RESTful servlet to get a decision. * * @param file/*from w w w .jav a2s. c om*/ * @return */ protected Response callRESTfulPDP(InputStream is) { Response response = null; HttpURLConnection connection = null; try { // // Open up the connection // connection = (HttpURLConnection) this.restURL.openConnection(); connection.setRequestProperty("Content-Type", "application/json"); // // Setup our method and headers // connection.setRequestMethod("POST"); connection.setUseCaches(false); // // Adding this in. It seems the HttpUrlConnection class does NOT // properly forward our headers for POST re-direction. It does so // for a GET re-direction. // // So we need to handle this ourselves. // connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setDoInput(true); // // Send the request // try (OutputStream os = connection.getOutputStream()) { IOUtils.copy(is, os); } // // Do the connect // connection.connect(); if (connection.getResponseCode() == 200) { // // Read the response // ContentType contentType = null; try { contentType = ContentType.parse(connection.getContentType()); if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { response = JSONResponse.load(connection.getInputStream()); } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { response = DOMResponse.load(connection.getInputStream()); } else { logger.error("unknown content-type: " + contentType); } } catch (Exception e) { String message = "Parsing Content-Type: " + connection.getContentType() + ", error=" + e.getMessage(); logger.error(message, e); } } else { logger.error(connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (Exception e) { logger.error(e); } return response; }