List of usage examples for java.net HttpURLConnection setUseCaches
public void setUseCaches(boolean usecaches)
From source file:models.cloud.notifications.gcm.Sender.java
/** * Make an HTTP post to a given URL.// ww w.j a v a 2 s . co m * * @return HTTP response. */ protected HttpURLConnection post(String url, String contentType, String body) throws IOException { if (url == null || body == null) { throw new IllegalArgumentException("arguments cannot be null"); } play.Logger.info(url); if (!url.startsWith("https://")) { logger.warning("URL does not use https: " + url); } logger.fine("Sending POST to " + url); logger.finest("POST body: " + body); byte[] bytes = body.getBytes(HTTP.UTF_8); HttpURLConnection conn = getConnection(url); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("Authorization", "key=" + key); OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); return conn; }
From source file:edu.pdx.cecs.orcycle.UserFeedbackUploader.java
boolean uploadUserInfoV4() { boolean result = false; final String postUrl = mCtx.getResources().getString(R.string.post_url); try {/*from w w w . ja v a2s . com*/ URL url = new URL(postUrl); HttpURLConnection 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("Cycleatl-Protocol-Version", "4"); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); JSONObject jsonUser; if (null != (jsonUser = getUserJSON())) { try { String deviceId = userId; dos.writeBytes(fieldSep + ContentField("user") + jsonUser.toString() + "\r\n"); dos.writeBytes( fieldSep + ContentField("version") + String.valueOf(kSaveProtocolVersion4) + "\r\n"); dos.writeBytes(fieldSep + ContentField("device") + deviceId + "\r\n"); dos.writeBytes(fieldSep); dos.flush(); } catch (Exception ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } finally { dos.close(); } int serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); // JSONObject responseData = new JSONObject(serverResponseMessage); Log.v("Jason", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 201 || serverResponseCode == 202) { // TODO: Record somehow that data was uploaded successfully result = true; } } else { result = false; } } catch (IllegalStateException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } catch (JSONException e) { e.printStackTrace(); return false; } return result; }
From source file:com.streamsets.pipeline.stage.origin.httpserver.TestHttpServerPushSource.java
@Test public void testSource() throws Exception { RawHttpConfigs httpConfigs = new RawHttpConfigs(); httpConfigs.appId = () -> "id"; httpConfigs.port = NetworkUtils.getRandomPort(); httpConfigs.maxConcurrentRequests = 1; httpConfigs.tlsConfigBean.tlsEnabled = false; HttpServerPushSource source = new HttpServerPushSource(httpConfigs, 1, DataFormat.TEXT, new DataParserFormatConfig()); final PushSourceRunner runner = new PushSourceRunner.Builder(HttpServerDPushSource.class, source) .addOutputLane("a").build(); runner.runInit();/*from w ww . j a v a 2s. co m*/ try { final List<Record> records = new ArrayList<>(); runner.runProduce(Collections.<String, String>emptyMap(), 1, new PushSourceRunner.Callback() { @Override public void processBatch(StageRunner.Output output) { records.clear(); records.addAll(output.getRecords().get("a")); } }); // wait for the HTTP server up and running HttpReceiverServer httpServer = (HttpReceiverServer) Whitebox.getInternalState(source, "server"); await().atMost(Duration.TEN_SECONDS).until(isServerRunning(httpServer)); HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:" + httpConfigs.getPort()) .openConnection(); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setDoOutput(true); connection.setRequestProperty(Constants.X_SDC_APPLICATION_ID_HEADER, "id"); connection.setRequestProperty("customHeader", "customHeaderValue"); connection.getOutputStream().write("Hello".getBytes()); Assert.assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode()); Assert.assertEquals(1, records.size()); Assert.assertEquals("Hello", records.get(0).get("/text").getValue()); Assert.assertEquals("id", records.get(0).getHeader().getAttribute(Constants.X_SDC_APPLICATION_ID_HEADER)); Assert.assertEquals("customHeaderValue", records.get(0).getHeader().getAttribute("customHeader")); // passing App Id via query param should fail when appIdViaQueryParamAllowed is false String url = "http://localhost:" + httpConfigs.getPort() + "?" + HttpConstants.SDC_APPLICATION_ID_QUERY_PARAM + "=id"; Response response = ClientBuilder.newClient().target(url).request().post(Entity.json("Hello")); Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, response.getStatus()); runner.setStop(); } catch (Exception e) { Assert.fail(e.getMessage()); } finally { runner.runDestroy(); } }
From source file:edu.illinois.cs.cogcomp.pipeline.server.ServerClientAnnotator.java
/** * The method is synchronized since the caching seems to have issues upon mult-threaded caching * @param overwrite if true, it would overwrite the values on cache *//*from w w w . ja va2 s. co m*/ public synchronized TextAnnotation annotate(String str, boolean overwrite) throws Exception { String viewsConnected = Arrays.toString(viewsToAdd); String views = viewsConnected.substring(1, viewsConnected.length() - 1).replace(" ", ""); ConcurrentMap<String, byte[]> concurrentMap = (db != null) ? db.hashMap(viewName, Serializer.STRING, Serializer.BYTE_ARRAY).createOrOpen() : null; String key = DigestUtils.sha1Hex(str + views); if (!overwrite && concurrentMap != null && concurrentMap.containsKey(key)) { byte[] taByte = concurrentMap.get(key); return SerializationHelper.deserializeTextAnnotationFromBytes(taByte); } else { URL obj = new URL(url + ":" + port + "/annotate"); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("charset", "utf-8"); con.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); con.setDoOutput(true); con.setUseCaches(false); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write("text=" + URLEncoder.encode(str, "UTF-8") + "&views=" + views); wr.flush(); InputStreamReader reader = new InputStreamReader(con.getInputStream()); BufferedReader in = new BufferedReader(reader); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); reader.close(); wr.close(); con.disconnect(); TextAnnotation ta = SerializationHelper.deserializeFromJson(response.toString()); if (concurrentMap != null) { concurrentMap.put(key, SerializationHelper.serializeTextAnnotationToBytes(ta)); this.db.commit(); } return ta; } }
From source file:com.yahoo.druid.hadoop.DruidInputFormat.java
private String getSegmentsToLoad(String dataSource, Interval interval, String overlordUrl) { String urlStr = "http://" + overlordUrl + "/druid/indexer/v1/action"; logger.info("Sending request to overlord at " + urlStr); String requestJson = getSegmentListUsedActionJson(dataSource, interval.toString()); logger.info("request json is " + requestJson); int numTries = 3; for (int trial = 0; trial < numTries; trial++) { try {//from w ww .j av a 2s .c o m logger.info("attempt number {} to get list of segments from overlord", trial); URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("content-type", "application/json"); conn.setRequestProperty("Accept", "*/*"); conn.setUseCaches(false); conn.setDoOutput(true); conn.setConnectTimeout(60000); OutputStream out = conn.getOutputStream(); out.write(requestJson.getBytes()); out.close(); int responseCode = conn.getResponseCode(); if (responseCode == 200) { return IOUtils.toString(conn.getInputStream()); } else { logger.warn( "Attempt Failed to get list of segments from overlord. response code [%s] , response [%s]", responseCode, IOUtils.toString(conn.getInputStream())); } } catch (Exception ex) { logger.warn("Exception in getting list of segments from overlord", ex); } try { Thread.sleep(5000); //wait before next trial } catch (InterruptedException ex) { Throwables.propagate(ex); } } throw new RuntimeException( String.format("failed to find list of segments, dataSource[%s], interval[%s], overlord[%s]", dataSource, interval, overlordUrl)); }
From source file:com.nimbits.user.GoogleAuthentication.java
private HttpURLConnection getConnection(final String service, final EmailAddress username, final String password) throws IOException { final URL url = new URL(Path.PATH_GOOGLE_CLIENT_LOGIN); final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true);//from w w w. jav a 2 s. c om urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); urlConnection.setRequestProperty(Parameters.contentType.getText(), "application/x-www-form-urlencoded"); final StringBuilder content = new StringBuilder(); content.append("Email=").append(username.getValue()).append("&Passwd=").append(password).append("&service=") .append(service); final OutputStream outputStream = urlConnection.getOutputStream(); outputStream.write(content.toString().getBytes(Const.CONST_ENCODING)); outputStream.close(); return urlConnection; }
From source file:fr.insalyon.creatis.vip.datamanager.applet.upload.UploadFilesBusiness.java
@Override public void run() { try {//from www . j ava 2 s . c o m SwingUtilities.invokeAndWait(beforeRunnable); File fileToUpload = null; boolean single = true; if (dataList.size() == 1 && new File(dataList.get(0)).isFile()) { fileToUpload = new File(dataList.get(0)); } else { String fileName = System.getProperty("java.io.tmpdir") + "/file-" + System.nanoTime() + ".zip"; FolderZipper.zipListOfData(dataList, fileName); fileToUpload = new File(fileName); zipFileName = fileToUpload.getName(); single = false; } // Call Servlet URL servletURL = new URL(codebase + "/fr.insalyon.creatis.vip.portal.Main/uploadfilesservice"); HttpURLConnection servletConnection = (HttpURLConnection) servletURL.openConnection(); servletConnection.setDoInput(true); servletConnection.setDoOutput(true); servletConnection.setUseCaches(false); servletConnection.setDefaultUseCaches(false); servletConnection.setChunkedStreamingMode(4096); servletConnection.setRequestProperty("vip-cookie-session", sessionId); servletConnection.setRequestProperty("Content-Type", "application/octet-stream"); servletConnection.setRequestProperty("Content-Length", Long.toString(fileToUpload.length())); servletConnection.setRequestProperty("path", path); servletConnection.setRequestProperty("fileName", fileToUpload.getName()); servletConnection.setRequestProperty("single", single + ""); servletConnection.setRequestProperty("unzip", unzip + ""); servletConnection.setRequestProperty("pool", usePool + ""); long fileSize = fileToUpload.length(); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileToUpload)); OutputStream os = servletConnection.getOutputStream(); try { byte[] buffer = new byte[4096]; long done = 0; while (true) { int bytes = bis.read(buffer); if (bytes < 0) { break; } done += bytes; os.write(buffer, 0, bytes); progressRunnable.setValue((int) (done * 100 / fileSize)); SwingUtilities.invokeAndWait(progressRunnable); } os.flush(); } finally { os.close(); bis.close(); } BufferedReader reader = new BufferedReader(new InputStreamReader(servletConnection.getInputStream())); String operationID = null; try { String line; while ((line = reader.readLine()) != null) { if (line.startsWith("id=")) { operationID = line.split("=")[1]; } System.out.println(line); } } finally { reader.close(); } if (!single) { fileToUpload.delete(); } if (deleteDataList) { for (String data : dataList) { FileUtils.deleteQuietly(new File(data)); } } result = operationID; SwingUtilities.invokeAndWait(afterRunnable); } catch (Exception ex) { result = ex.getMessage(); SwingUtilities.invokeLater(errorRunnable); } }
From source file:com.zlk.bigdemo.android.volley.toolbox.HurlStack.java
/** * Opens an {@link HttpURLConnection} with parameters. * @param url/*from w ww. jav a 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()) && mSslSocketFactory != null) { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory); } return connection; }
From source file:ly.count.android.api.ConnectionProcessor.java
URLConnection urlConnectionForEventData(final String eventData) throws IOException { final String urlStr = serverURL_ + "/i?" + eventData; final URL url = new URL(urlStr); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(CONNECT_TIMEOUT_IN_MILLISECONDS); conn.setReadTimeout(READ_TIMEOUT_IN_MILLISECONDS); conn.setUseCaches(false); conn.setDoInput(true);//from w w w . ja v a2s . c o m String picturePath = UserData.getPicturePathFromQuery(url); if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Got picturePath: " + picturePath); } if (!picturePath.equals("")) { //Uploading files: //http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests File binaryFile = new File(picturePath); conn.setDoOutput(true); // Just generate some unique random value. String boundary = Long.toHexString(System.currentTimeMillis()); // Line separator required by multipart/form-data. String CRLF = "\r\n"; String charset = "UTF-8"; conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream output = conn.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // Send binary file. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())) .append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append(CRLF).flush(); FileInputStream fileInputStream = new FileInputStream(binaryFile); byte[] buffer = new byte[1024]; int len; while ((len = fileInputStream.read(buffer)) != -1) { output.write(buffer, 0, len); } output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. fileInputStream.close(); // End of multipart/form-data. writer.append("--" + boundary + "--").append(CRLF).flush(); } else { conn.setDoOutput(false); } return conn; }
From source file:com.wareninja.android.commonutils.foursquareV2.http.AbstractHttpApi.java
public HttpURLConnection createHttpURLConnectionPost(URL url, String boundary) throws IOException { //-WareNinjaUtils.trustEveryone();//YG HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true);//from w w w . j av a2 s . c o m conn.setDoOutput(true); conn.setUseCaches(false); conn.setConnectTimeout(TIMEOUT * 1000); conn.setRequestMethod("POST"); conn.setRequestProperty(CLIENT_VERSION_HEADER, mClientVersion); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); return conn; }