List of usage examples for java.net HttpURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
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 ww w .j a v 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:loadTest.loadTestLib.LUtil.java
public static boolean startDockerBuild() throws IOException, InterruptedException { if (useDocker) { if (runInDockerCluster) { HashMap<String, Integer> dockerNodes = getDockerNodes(); String dockerTar = LUtil.class.getClassLoader().getResource("docker/loadTest.tar").toString() .substring(5);// w w w . java 2 s . co m ExecutorService exec = Executors.newFixedThreadPool(dockerNodes.size()); dockerError = false; doneDockers = 0; for (Entry<String, Integer> entry : dockerNodes.entrySet()) { exec.submit(new Runnable() { @Override public void run() { try { String url = entry.getKey() + "/images/vauvenal5/loadtest"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("DELETE"); con.setRequestProperty("force", "true"); int responseCode = con.getResponseCode(); con.disconnect(); url = entry.getKey() + "/build?t=vauvenal5/loadtest&dockerfile=./loadTest/Dockerfile"; obj = new URL(url); con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "application/tar"); con.setDoOutput(true); File file = new File(dockerTar); FileInputStream fileStr = new FileInputStream(file); byte[] b = new byte[(int) file.length()]; fileStr.read(b); con.getOutputStream().write(b); con.getOutputStream().flush(); con.getOutputStream().close(); responseCode = con.getResponseCode(); if (responseCode != 200) { dockerError = true; } String msg = ""; do { Thread.sleep(5000); msg = ""; url = entry.getKey() + "/images/json"; obj = new URL(url); HttpURLConnection con2 = (HttpURLConnection) obj.openConnection(); con2.setRequestMethod("GET"); responseCode = con2.getResponseCode(); BufferedReader in = new BufferedReader( new InputStreamReader(con2.getInputStream())); String line = null; while ((line = in.readLine()) != null) { msg += line; } con2.disconnect(); } while (!msg.contains("vauvenal5/loadtest")); con.disconnect(); doneDockers++; } catch (MalformedURLException ex) { dockerError = true; } catch (FileNotFoundException ex) { dockerError = true; } catch (IOException ex) { dockerError = true; } catch (InterruptedException ex) { dockerError = true; } } }); } while (doneDockers < dockerNodes.size()) { Thread.sleep(5000); } return !dockerError; } //get the path and substring the 'file:' from the URI String dockerfile = LUtil.class.getClassLoader().getResource("docker/loadTest").toString().substring(5); ProcessBuilder processBuilder = new ProcessBuilder("docker", "rmi", "-f", "vauvenal5/loadtest"); processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT); Process docker = processBuilder.start(); docker.waitFor(); processBuilder = new ProcessBuilder("docker", "build", "-t", "vauvenal5/loadtest", dockerfile); processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT); Process proc = processBuilder.start(); return proc.waitFor() == 0; } return true; }
From source file:db.dao.ArticleDao.java
public void deletebyId(String deleteId) { try {//from w w w.java 2 s . c o m String url = this.checkIfLocal("article/delete"); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "id=" + URLEncoder.encode(deleteId); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); //print result System.out.println(responseCode); } catch (MalformedURLException ex) { Logger.getLogger(ArticleDao.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ArticleDao.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.joyent.manta.client.MantaClientSigningIT.java
@Test public final void testCanCreateSignedPUTUriFromPath() throws IOException, InterruptedException { if (config.isClientEncryptionEnabled()) { throw new SkipException("Signed URLs are not decrypted by the client"); }//w w w.j a v a 2 s . co m final String name = UUID.randomUUID().toString(); final String path = testPathPrefix + name; Instant expires = Instant.now().plus(1, ChronoUnit.HOURS); URI uri = mantaClient.getAsSignedURI(path, "PUT", expires); HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection(); connection.setReadTimeout(3000); connection.setRequestMethod("PUT"); connection.setDoOutput(true); connection.setChunkedStreamingMode(10); connection.connect(); try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), UTF_8)) { out.write(TEST_DATA); } finally { connection.disconnect(); } // Wait for file to become available for (int i = 0; i < 10; i++) { Thread.sleep(500); if (mantaClient.existsAndIsAccessible(path)) { break; } } String actual = mantaClient.getAsString(path); Assert.assertEquals(actual, TEST_DATA); }
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 {/*from w w w . j a v a 2s .c o 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.facebook.android.library.Util.java
/** * Connect to an HTTP URL and return the response as a string. * // w w w.j a va 2 s .c o m * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url * - the resource to open: must be a welformed URL * @param method * - the HTTP method to use ("GET", "POST", etc.) * @param params * - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String * @throws MalformedURLException * - if the URL format is invalid * @throws IOException * - if a network problem occurs */ public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os; if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } Util.logd("Facebook-Util", method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); if (!method.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { if (params.get(key) instanceof byte[]) { dataparams.putByteArray(key, params.getByteArray(key)); } } // use method override if (!params.containsKey("method")) { params.putString("method", method); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(params.getString("access_token")); params.putString("access_token", decoded_token); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + strBoundary + endLine).getBytes()); os.write((encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; }
From source file:junit.org.rapidpm.microservice.demo.ServletTest.java
@Test public void testServletPostRequest() throws Exception { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345"; // Send post request con.setDoOutput(true);/*from w ww . java 2 s .c o m*/ DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); 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(); //print result Assert.assertEquals("Hello World CDI Service", response.toString()); }
From source file:com.vmware.photon.controller.deployer.deployengine.DockerProvisioner.java
public void createImageFromTar(String filePath, String imageName) { if (StringUtils.isBlank(imageName)) { throw new IllegalArgumentException("imageName field cannot be null or blank"); }// w w w .jav a2s . c o m if (StringUtils.isBlank(filePath)) { throw new IllegalArgumentException("filePath field cannot be null or blank"); } File tarFile = new File(filePath); try (FileInputStream fileInputStream = new FileInputStream(tarFile)) { FileChannel in = fileInputStream.getChannel(); String endpoint = getImageLoadEndpoint(); URL url = new URL(endpoint); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Accept", "application/json"); connection.setDoOutput(true); WritableByteChannel out = Channels.newChannel(connection.getOutputStream()); in.transferTo(0, tarFile.length(), out); in.close(); out.close(); int responseCode = connection.getResponseCode(); if (!String.valueOf(responseCode).startsWith("2")) { throw new RuntimeException( "Docker Endpoint cannot load image from tar. Failed with response code " + responseCode); } } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.bjorsond.android.timeline.sync.ServerUploader.java
protected static void uploadFile(String locationFilename, String saveFilename) { System.out.println("saving " + locationFilename + "!! "); if (!saveFilename.contains(".")) saveFilename = saveFilename + Utilities.getExtension(locationFilename); if (!fileExistsOnServer(saveFilename)) { HttpURLConnection connection = null; DataOutputStream outputStream = null; String pathToOurFile = locationFilename; String urlServer = "http://folk.ntnu.no/bjornava/upload/upload.php"; // String urlServer = "http://timelinegamified.appspot.com/upload.php"; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024 * 1024; try {//from w ww. ja va 2 s . c o m FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile)); URL url = new URL(urlServer); connection = (HttpURLConnection) url.openConnection(); // Allow Inputs & Outputs connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); // Enable POST method connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); 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=\"uploadedfile\";filename=\"" + saveFilename + "\"" + lineEnd); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // Read file 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); // Responses from the server (code and message) int serverResponseCode = connection.getResponseCode(); String serverResponseMessage = connection.getResponseMessage(); fileInputStream.close(); outputStream.flush(); outputStream.close(); System.out.println("Server response: " + serverResponseCode + " Message: " + serverResponseMessage); } catch (Exception ex) { //Exception handling } } else { System.out.println("image exists on server"); } }
From source file:net.gcolin.simplerepo.test.AbstractRepoTest.java
protected int sendContent(String url, String fileContent, String user, String password) throws IOException { HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection(); try {//from w w w .ja va 2 s . c om c.setDoOutput(true); c.setRequestMethod("PUT"); if (user != null) { c.setRequestProperty("Authorization", "Basic " + Base64.encodeBase64String((user + ":" + password).getBytes("utf-8"))); } c.connect(); IOUtils.copy(new ByteArrayInputStream(fileContent.getBytes("utf-8")), c.getOutputStream()); return c.getResponseCode(); } finally { c.disconnect(); } }