Tabnine Logo
HttpURLConnection.getOutputStream
Code IndexAdd Tabnine to your IDE (free)

How to use
getOutputStream
method
in
java.net.HttpURLConnection

Best Java code snippets using java.net.HttpURLConnection.getOutputStream (Showing top 20 results out of 11,178)

Refine searchRefine arrow

  • HttpURLConnection.setDoOutput
  • HttpURLConnection.setRequestMethod
  • URL.openConnection
  • HttpURLConnection.setRequestProperty
  • HttpURLConnection.getInputStream
  • URL.<init>
canonical example by Tabnine

public void postRequest(String urlStr, String jsonBodyStr) throws IOException {
  URL url = new URL(urlStr);
  HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
  httpURLConnection.setDoOutput(true);
  httpURLConnection.setRequestMethod("POST");
  httpURLConnection.setRequestProperty("Content-Type", "application/json");
  try (OutputStream outputStream = httpURLConnection.getOutputStream()) { 
   outputStream.write(jsonBodyStr.getBytes());
   outputStream.flush();
  }
  if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
    try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()))) {
      String line;
      while ((line = bufferedReader.readLine()) != null) {
        // ... do something with line
      }
    }
  } else {
    // ... do something with unsuccessful response
  }
}
origin: google/physical-web

/**
 * Helper method to make an HTTP request.
 * @param urlConnection The HTTP connection.
 */
public void writeToUrlConnection(HttpURLConnection urlConnection) throws IOException {
 urlConnection.setDoOutput(true);
 urlConnection.setRequestProperty("Content-Type", "application/json");
 urlConnection.setRequestProperty("Accept", "application/json");
 urlConnection.setRequestMethod("POST");
 OutputStream os = urlConnection.getOutputStream();
 os.write(mJsonObject.toString().getBytes("UTF-8"));
 os.close();
}
origin: mcxiaoke/android-volley

  private static void addBodyIfExists(HttpURLConnection connection, Request<?> request)
      throws IOException, AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
      connection.setDoOutput(true);
      connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
      DataOutputStream out = new DataOutputStream(connection.getOutputStream());
      out.write(body);
      out.close();
    }
  }
}
origin: ACRA/acra

@SuppressWarnings("WeakerAccess")
protected void writeContent(@NonNull HttpURLConnection connection, @NonNull Method method, @NonNull T content) throws IOException {
  // write output - see http://developer.android.com/reference/java/net/HttpURLConnection.html
  connection.setRequestMethod(method.name());
  connection.setDoOutput(true);
  // Disable ConnectionPooling because otherwise OkHttp ConnectionPool will try to start a Thread on #connect
  System.setProperty("http.keepAlive", "false");
  connection.connect();
  final OutputStream outputStream = senderConfiguration.compress() ? new GZIPOutputStream(connection.getOutputStream(), ACRAConstants.DEFAULT_BUFFER_SIZE_IN_BYTES)
      : new BufferedOutputStream(connection.getOutputStream());
  try {
    write(outputStream, content);
    outputStream.flush();
  } finally {
    IOUtils.safeClose(outputStream);
  }
}
origin: wildfly/wildfly

try {
  if (inputData != null) {
    urlConnection.setDoOutput(true);
    outputStream = urlConnection.getOutputStream();
    outputStream.write(inputData);
    inputStream = urlConnection.getInputStream();
    payload = Util.readFileContents(urlConnection.getInputStream());
origin: voldemort/voldemort

                     routingType,
                     "POST");
conn.setDoOutput(true);
if(vectorClock != null) {
  conn.setRequestProperty(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, vectorClock);
  conn.setRequestProperty("Content-Type", ContentType);
  conn.setRequestProperty("Content-Length", contentLength);
  OutputStream out = conn.getOutputStream();
  out.write(value.getBytes());
  out.close();
origin: spotify/helios

 private HttpURLConnection post(final String path, final byte[] body) throws IOException {
  final URL url = new URL(masterEndpoint() + path);
  final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod("POST");
  connection.setRequestProperty("Content-Type", "application/json");
  connection.setDoInput(true);
  connection.setDoOutput(true);
  connection.getOutputStream().write(body);
  return connection;
 }
}
origin: chentao0707/SimplifyReader

  private static void addBodyIfExists(HttpURLConnection connection, Request<?> request)
      throws IOException, AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
      connection.setDoOutput(true);
      connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
      DataOutputStream out = new DataOutputStream(connection.getOutputStream());
      out.write(body);
      out.close();
    }
  }
}
origin: javamelody/javamelody

public void post(ByteArrayOutputStream payload) throws IOException {
  final HttpURLConnection connection = (HttpURLConnection) openConnection();
  connection.setRequestMethod("POST");
  connection.setDoOutput(true);
  if (payload != null) {
    final OutputStream outputStream = connection.getOutputStream();
    payload.writeTo(outputStream);
    outputStream.flush();
  }
  final int status = connection.getResponseCode();
  if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
    final String error = InputOutput.pumpToString(connection.getErrorStream(),
        Charset.forName("UTF-8"));
    final String msg = "Error connecting to " + url + '(' + status + "): " + error;
    throw new IOException(msg);
  }
  connection.disconnect();
}
origin: wildfly/wildfly

try {
  if (inputData != null) {
    urlConnection.setDoOutput(true);
    outputStream = urlConnection.getOutputStream();
    outputStream.write(inputData);
    payload = getBytes(urlConnection.getInputStream());
origin: googleapis/google-cloud-java

protected final String sendPostRequest(String request) throws IOException {
 URL url = new URL("http", DEFAULT_HOST, this.port, request);
 HttpURLConnection con = (HttpURLConnection) url.openConnection();
 con.setRequestMethod("POST");
 con.setDoOutput(true);
 OutputStream out = con.getOutputStream();
 out.write("".getBytes());
 out.flush();
 InputStream in = con.getInputStream();
 String response = CharStreams.toString(new InputStreamReader(con.getInputStream()));
 in.close();
 return response;
}
origin: jiangqqlmj/FastDev4Android

  private static void addBodyIfExists(HttpURLConnection connection, Request<?> request)
      throws IOException, AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
      connection.setDoOutput(true);
      connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
      DataOutputStream out = new DataOutputStream(connection.getOutputStream());
      out.write(body);
      out.close();
    }
  }
}
origin: google/agera

@NonNull
private HttpResponse getHttpResponseResult(final @NonNull HttpRequest request,
  @NonNull final HttpURLConnection connection) throws IOException {
 connection.setConnectTimeout(request.connectTimeoutMs);
 connection.setReadTimeout(request.readTimeoutMs);
 connection.setInstanceFollowRedirects(request.followRedirects);
 connection.setUseCaches(request.useCaches);
 connection.setDoInput(true);
 connection.setRequestMethod(request.method);
 for (final Entry<String, String> headerField : request.header.entrySet()) {
  connection.addRequestProperty(headerField.getKey(), headerField.getValue());
 }
 final byte[] body = request.body;
 if (body.length > 0) {
  connection.setDoOutput(true);
  final OutputStream out = connection.getOutputStream();
  try {
   out.write(body);
  } finally {
   out.close();
  }
 }
 final String responseMessage = connection.getResponseMessage();
 return httpResponse(connection.getResponseCode(),
   responseMessage != null ? responseMessage : "",
   getHeader(connection), getByteArray(connection));
}
origin: languagetool-org/languagetool

@NotNull
private HttpURLConnection postToServer(String json, URL url) throws IOException {
 HttpURLConnection conn = (HttpURLConnection)url.openConnection();
 conn.setRequestMethod("POST");
 conn.setUseCaches(false);
 conn.setRequestProperty("Content-Type", "application/json");
 conn.setDoOutput(true);
 try {
  try (DataOutputStream dos = new DataOutputStream(conn.getOutputStream())) {
   //System.out.println("POSTING: " + json);
   dos.write(json.getBytes("utf-8"));
  }
 } catch (IOException e) {
  throw new RuntimeException("Could not connect OpenNMT server at " + url);
 }
 return conn;
}
origin: wildfly/wildfly

public Response put(String preSignedUrl, S3Object object, Map headers) throws IOException {
  HttpURLConnection request = makePreSignedRequest("PUT", preSignedUrl, headers);
  request.setDoOutput(true);
  request.getOutputStream().write(object.data == null? new byte[]{} : object.data);
  return new Response(request);
}
origin: testcontainers/testcontainers-java

public void callCouchbaseRestAPI(String url, String payload) throws IOException {
  String fullUrl = urlBase + url;
  @Cleanup("disconnect")
  HttpURLConnection httpConnection = (HttpURLConnection) ((new URL(fullUrl).openConnection()));
  httpConnection.setDoOutput(true);
  httpConnection.setRequestMethod("POST");
  httpConnection.setRequestProperty("Content-Type",
    "application/x-www-form-urlencoded");
  String encoded = Base64.encode((clusterUsername + ":" + clusterPassword).getBytes("UTF-8"));
  httpConnection.setRequestProperty("Authorization", "Basic " + encoded);
  @Cleanup
  DataOutputStream out = new DataOutputStream(httpConnection.getOutputStream());
  out.writeBytes(payload);
  out.flush();
  httpConnection.getResponseCode();
}
origin: spring-projects/spring-framework

@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException {
  addHeaders(this.connection, headers);
  // JDK <1.8 doesn't support getOutputStream with HTTP DELETE
  if (getMethod() == HttpMethod.DELETE && bufferedOutput.length == 0) {
    this.connection.setDoOutput(false);
  }
  if (this.connection.getDoOutput() && this.outputStreaming) {
    this.connection.setFixedLengthStreamingMode(bufferedOutput.length);
  }
  this.connection.connect();
  if (this.connection.getDoOutput()) {
    FileCopyUtils.copy(bufferedOutput, this.connection.getOutputStream());
  }
  else {
    // Immediately trigger the request in a no-output scenario as well
    this.connection.getResponseCode();
  }
  return new SimpleClientHttpResponse(this.connection);
}
origin: sohutv/cachecloud

private static HttpURLConnection sendPost(String reqUrl,
    Map<String, String> parameters, String encoding, int connectTimeout, int readTimeout) {
  HttpURLConnection urlConn = null;
  try {
    String params = generatorParamString(parameters, encoding);
    URL url = new URL(reqUrl);
    urlConn = (HttpURLConnection) url.openConnection();
    urlConn.setRequestMethod("POST");
    // urlConn
    // .setRequestProperty(
    // "User-Agent",
    // "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3");
    urlConn.setConnectTimeout(connectTimeout);// (单位:毫秒)jdk
    urlConn.setReadTimeout(readTimeout);// (单位:毫秒)jdk 1.5换成这个,读操作超时
    urlConn.setDoOutput(true);
    // String按照字节处理是一个好方法
    byte[] b = params.getBytes(encoding);
    urlConn.getOutputStream().write(b, 0, b.length);
    urlConn.getOutputStream().flush();
    urlConn.getOutputStream().close();
  } catch (Exception e) {
    logger.error(e.getMessage(), e);
  }
  return urlConn;
}
origin: spring-projects/spring-framework

  @Override
  public ClientHttpResponse call() throws Exception {
    SimpleBufferingClientHttpRequest.addHeaders(connection, headers);
    // JDK <1.8 doesn't support getOutputStream with HTTP DELETE
    if (getMethod() == HttpMethod.DELETE && bufferedOutput.length == 0) {
      connection.setDoOutput(false);
    }
    if (connection.getDoOutput() && outputStreaming) {
      connection.setFixedLengthStreamingMode(bufferedOutput.length);
    }
    connection.connect();
    if (connection.getDoOutput()) {
      FileCopyUtils.copy(bufferedOutput, connection.getOutputStream());
    }
    else {
      // Immediately trigger the request in a no-output scenario as well
      connection.getResponseCode();
    }
    return new SimpleClientHttpResponse(connection);
  }
});
origin: ethereum/ethereumj

private String postQuery(String endPoint, String json) throws IOException {
  URL url = new URL(endPoint);
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  conn.setConnectTimeout(5000);
  conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
  conn.setDoOutput(true);
  conn.setDoInput(true);
  conn.setRequestMethod("POST");
  OutputStream os = conn.getOutputStream();
  os.write(json.getBytes("UTF-8"));
  os.close();
  // read the response
  InputStream in = new BufferedInputStream(conn.getInputStream());
  String result = null;
  try (Scanner scanner = new Scanner(in, "UTF-8")) {
    result =  scanner.useDelimiter("\\A").next();
  }
  in.close();
  conn.disconnect();
  return result;
}
java.netHttpURLConnectiongetOutputStream

Popular methods of HttpURLConnection

  • getInputStream
  • getResponseCode
    Returns the response code returned by the remote HTTP server.
  • setRequestMethod
    Sets the request command which will be sent to the remote HTTP server. This method can only be calle
  • setRequestProperty
  • setDoOutput
  • disconnect
    Releases this connection so that its resources may be either reused or closed. Unlike other Java imp
  • setConnectTimeout
  • connect
  • setReadTimeout
  • getErrorStream
    Returns an input stream from the server in the case of an error such as the requested file has not b
  • setDoInput
  • getResponseMessage
    Returns the response message returned by the remote HTTP server.
  • setDoInput,
  • getResponseMessage,
  • getHeaderField,
  • setUseCaches,
  • setInstanceFollowRedirects,
  • getHeaderFields,
  • addRequestProperty,
  • getContentLength,
  • getURL

Popular in Java

  • Making http post requests using okhttp
  • getContentResolver (Context)
  • putExtra (Intent)
  • runOnUiThread (Activity)
  • Socket (java.net)
    Provides a client-side TCP socket.
  • Path (java.nio.file)
  • SortedMap (java.util)
    A map that has its keys ordered. The sorting is according to either the natural ordering of its keys
  • HttpServletRequest (javax.servlet.http)
    Extends the javax.servlet.ServletRequest interface to provide request information for HTTP servlets.
  • JComboBox (javax.swing)
  • JLabel (javax.swing)
  • Github Copilot alternatives
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now