List of usage examples for java.net HttpURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:com.gmail.tracebachi.DeltaSkins.Shared.MojangApi.java
public JsonArray getUuids() throws IOException, RateLimitedException { synchronized (uuidRequestLock) { // If requests are empty, do not make a request if (uuidRequests.size() <= 0) { return new JsonArray(); }//from w w w .j a va2s . c o m } String stringPayload = convertUuidRequestsToStringPayload(); HttpURLConnection httpConn = openNameToIdConnection(); httpConn.setRequestMethod("POST"); httpConn.setRequestProperty("Content-Type", "application/json"); OutputStream outputStream = httpConn.getOutputStream(); byte[] payload = stringPayload.getBytes(StandardCharsets.UTF_8); outputStream.write(payload); outputStream.flush(); outputStream.close(); plugin.debugApi("[Payload] " + stringPayload); if (httpConn.getResponseCode() == 429) { throw new RateLimitedException(); } StringWriter writer = new StringWriter(); InputStream inputStream = httpConn.getInputStream(); IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8); inputStream.close(); String response = writer.toString(); writer.close(); plugin.debugApi("[Response] " + response); synchronized (parserLock) { return parser.parse(response).getAsJsonArray(); } }
From source file:squash.deployment.lambdas.utils.CloudFormationResponder.java
/** * Sends the custom resource response to the Cloudformation service. * // w w w .j a v a2s . com * <p>The response is returned indirectly to Cloudformation via the * presigned Url it provided in its request. * * @param status whether the call succeeded - must be either SUCCESS or FAILED. * @param logger a CloudwatchLogs logger. * @throws IllegalStateException when the responder is uninitialised. */ public void sendResponse(String status, LambdaLogger logger) { if (!initialised) { throw new IllegalStateException("The responder has not been initialised"); } try { rootNode.put("Status", status); rootNode.put("RequestId", requestParameters.get("RequestId")); rootNode.put("StackId", requestParameters.get("StackId")); rootNode.put("LogicalResourceId", requestParameters.get("LogicalResourceId")); rootNode.put("PhysicalResourceId", physicalResourceId); } catch (Exception e) { // Can do nothing more than log the error and return. Must rely on // CloudFormation timing-out since it won't get a response from us. logger.log("Exception caught whilst constructing response: " + e.toString()); return; } // Send the response to CloudFormation via the provided presigned S3 URL logger.log("About to send response to presigned URL: " + requestParameters.get("ResponseURL")); try { URL url = new URL(requestParameters.get("ResponseURL")); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("PUT"); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); mapper.writeTree(generator, rootNode); String output = cloudFormationJsonResponse.toString(StandardCharsets.UTF_8.name()); logger.log("Response about to be sent: " + output); out.write(output); out.close(); logger.log("Sent response to presigned URL"); int responseCode = connection.getResponseCode(); logger.log("Response Code returned from presigned URL: " + responseCode); } catch (IOException e) { // Can do nothing more than log the error and return. logger.log("Exception caught whilst replying to presigned URL: " + e.toString()); return; } }
From source file:de.hybris.platform.marketplaceintegration.utils.impl.MarketplaceintegrationHttpUtilImpl.java
/** * Post data/*from w w w .j a v a 2 s . c o m*/ * * @param url * @param data * @return boolean * @throws IOException */ @Override public boolean post(final String url, final String data) throws IOException { httpURL = new URL(url); final HttpURLConnection conn = (HttpURLConnection) httpURL.openConnection(); conn.setDoOutput(true); initConnection(conn); OutputStreamWriter writer = null; try { writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); } finally { if (writer != null) { try { writer.close(); } catch (final IOException ex) { LOG.error(ex.getMessage(), ex); } } } final int status = conn.getResponseCode(); conn.disconnect(); return status == HttpURLConnection.HTTP_OK; }
From source file:com.google.gwt.benchmark.compileserver.server.manager.BenchmarkReporter.java
private boolean postResultToServer(String json) { OutputStream out = null;// ww w . j a v a 2 s . c o m try { HttpURLConnection httpCon = httpURLConnectionFactory.create(); httpCon.addRequestProperty("auth", reporterSecret); httpCon.setDoOutput(true); httpCon.setRequestMethod("PUT"); out = httpCon.getOutputStream(); out.write(json.getBytes("UTF-8")); if (httpCon.getResponseCode() == HTTP_OK) { return true; } } catch (IOException e) { logger.log(Level.WARNING, "Could not post results to server", e); } finally { IOUtils.closeQuietly(out); } return false; }
From source file:net.sf.okapi.filters.drupal.DrupalConnector.java
public boolean updateNode(Node node) { try {/*from ww w . j av a 2s . c o m*/ URL url = new URL(host + String.format("rest/node/" + node.getNid())); HttpURLConnection conn = createConnection(url, "PUT", true); OutputStream os = conn.getOutputStream(); os.write(node.toString().getBytes()); os.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { System.out.println(conn.getResponseCode()); System.out.println(conn.getResponseMessage()); throw new RuntimeException("Operation failed: " + conn.getResponseCode()); } conn.disconnect(); return true; } catch (Throwable e) { throw new RuntimeException("Error in updateNode(): " + e.getMessage(), e); } }
From source file:net.sf.okapi.filters.drupal.DrupalConnector.java
public boolean postNode(Node node) { try {//from ww w. j a v a2 s .c om URL url = new URL(host + String.format("rest/node")); HttpURLConnection conn = createConnection(url, "POST", true); OutputStream os = conn.getOutputStream(); os.write(node.toString().getBytes()); os.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { System.out.println(conn.getResponseCode()); System.out.println(conn.getResponseMessage()); throw new RuntimeException("Operation failed: " + conn.getResponseCode()); } conn.disconnect(); return true; } catch (Throwable e) { throw new RuntimeException("Error in postNode(): " + e.getMessage(), e); } }
From source file:at.florian_lentsch.expirysync.net.JsonCaller.java
private void writeParams(HttpURLConnection connection, JSONObject params) throws IOException, JSONException, UnsupportedEncodingException { OutputStream os = connection.getOutputStream(); final OutputStreamWriter osw = new OutputStreamWriter(os); final String toWriteOut = params.toString(); osw.write(toWriteOut);/* w w w . j ava2 s. c om*/ osw.close(); }
From source file:com.adamrosenfield.wordswithcrosses.net.DerStandardDownloader.java
private HttpURLConnection getHttpPostConnection(String url, String postData) throws IOException, MalformedURLException { HttpURLConnection conn = getHttpConnection(url); conn.setRequestMethod("POST"); conn.setDoOutput(true);//from w ww . j a va 2 s . c om OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream()); try { osw.append(postData); } finally { osw.close(); } return conn; }
From source file:com.vmanolache.mqttpolling.Polling.java
private void sendPost() throws UnsupportedEncodingException, JSONException { try {/*from www. j a v a2s . com*/ String url = "http://localhost:8080/notifications"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); HttpURLConnection connection = (HttpURLConnection) obj.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestMethod("POST"); /** * POSTing * */ OutputStream os = connection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(getQuery()); // should be fine if my getQuery is encoded right yes? writer.flush(); writer.close(); os.close(); connection.connect(); int status = connection.getResponseCode(); System.out.println(status); } catch (IOException ex) { Logger.getLogger(Polling.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:Main.java
public static String postMultiPart(String urlTo, String post, String filepath, String filefield) throws ParseException, IOException { 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; String[] q = filepath.split("/"); int idx = q.length - 1; try {//from ww w . j a v a2 s . c om File file = new File(filepath); FileInputStream fileInputStream = new FileInputStream(file); 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("User-Agent", "Android Multipart HTTP Client 1.0"); 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=\"" + q[idx] + "\"" + lineEnd); outputStream.writeBytes("Content-Type: image/jpeg" + 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); // Upload POST Data String[] posts = post.split("&"); int max = posts.length; for (int i = 0; i < max; i++) { outputStream.writeBytes(twoHyphens + boundary + lineEnd); String[] kv = posts[i].split("="); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + "\"" + lineEnd); outputStream.writeBytes("Content-Type: text/plain" + lineEnd); outputStream.writeBytes(lineEnd); outputStream.writeBytes(kv[1]); outputStream.writeBytes(lineEnd); } outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); inputStream = connection.getInputStream(); result = convertStreamToString(inputStream); fileInputStream.close(); inputStream.close(); outputStream.flush(); outputStream.close(); return result; } catch (Exception e) { Log.e("MultipartRequest", "Multipart Form Upload Error"); e.printStackTrace(); return "error"; } }