Example usage for java.net HttpURLConnection getOutputStream

List of usage examples for java.net HttpURLConnection getOutputStream

Introduction

In this page you can find the example usage for java.net HttpURLConnection getOutputStream.

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream that writes to this connection.

Usage

From source file:neal.http.impl.httpstack.HurlStack.java

@SuppressWarnings("deprecation")
/* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, HttpErrorCollection.AuthFailureError {
    switch (request.getMethod()) {
    case Request.Method.DEPRECATED_GET_OR_POST:
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            // Prepare output. There is no need to set Content-Length explicitly,
            // since this is handled by HttpURLConnection using the size of the prepared
            // output stream.
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(postBody);//w  w  w  . java  2  s .c o  m
            out.close();
        }
        break;
    case Method.GET:
        // Not necessary to set the request method because connection defaults to GET but
        // being explicit here.
        connection.setRequestMethod("GET");
        break;
    case Method.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case Method.POST:
        connection.setRequestMethod("POST");
        addBodyIfExists(connection, request);
        break;
    case Method.PUT:
        connection.setRequestMethod("PUT");
        addBodyIfExists(connection, request);
        break;
    case Method.HEAD:
        connection.setRequestMethod("HEAD");
        break;
    case Method.OPTIONS:
        connection.setRequestMethod("OPTIONS");
        break;
    case Method.TRACE:
        connection.setRequestMethod("TRACE");
        break;
    case Method.PATCH:
        connection.setRequestMethod("PATCH");
        addBodyIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:gmusic.api.comm.HttpUrlConnector.java

@Override
public String dispatchPost(URI address, String json) throws IOException, URISyntaxException {
    HttpURLConnection connection = prepareConnection(address, true, "POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.connect();/*from  w ww .j  av a2  s .  c  o m*/
    connection.getOutputStream().write(json.getBytes());
    if (connection.getResponseCode() != 200) {
        throw new IllegalStateException("Statuscode " + connection.getResponseCode() + " not supported");
    }

    String response = IOUtils.toString(connection.getInputStream());
    if (!isStartup) {
        return response;
    }
    return setupAuthentication(response);
}

From source file:com.miya38.connection.volley.CustomHurlStack.java

@SuppressWarnings("deprecation")
/* package */static void setConnectionParametersForRequest(final HttpURLConnection connection,
        final Request<?> request) throws IOException, AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST:
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        final byte[] postBody = request.getPostBody();
        if (postBody != null) {
            // Prepare output. There is no need to set Content-Length explicitly,
            // since this is handled by HttpURLConnection using the size of the prepared
            // output stream.
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            final DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(postBody);//  w  w w .  java  2 s .c o m
            out.close();
        }
        break;
    case Method.GET:
        // Not necessary to set the request method because connection defaults to GET but
        // being explicit here.
        connection.setRequestMethod("GET");
        break;
    case Method.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case Method.POST:
        connection.setRequestMethod("POST");
        addBodyIfExists(connection, request);
        break;
    case Method.PUT:
        connection.setRequestMethod("PUT");
        addBodyIfExists(connection, request);
        break;
    case Method.HEAD:
        connection.setRequestMethod("HEAD");
        break;
    case Method.OPTIONS:
        connection.setRequestMethod("OPTIONS");
        break;
    case Method.TRACE:
        connection.setRequestMethod("TRACE");
        break;
    case Method.PATCH:
        connection.setRequestMethod("PATCH");
        addBodyIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:org.apache.taverna.activities.interaction.InteractionUtils.java

void publishFile(final String urlString, final InputStream is, final String runId, final String interactionId)
        throws IOException {
    if (InteractionUtils.publishedUrls.contains(urlString)) {
        return;/*  w  w w . j a  v  a  2s  . com*/
    }
    InteractionUtils.publishedUrls.add(urlString);
    if (runId != null) {
        interactionRecorder.addResource(runId, interactionId, urlString);
    }

    final URL url = new URL(urlString);
    final HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    httpCon.setDoOutput(true);
    httpCon.setRequestMethod("PUT");
    final OutputStream outputStream = httpCon.getOutputStream();
    IOUtils.copy(is, outputStream);
    is.close();
    outputStream.close();
    int code = httpCon.getResponseCode();
    if ((code >= 400) || (code < 0)) {
        throw new IOException("Received code " + code);
    }
}

From source file:com.googlecode.osde.internal.igoogle.IgCredentials.java

/**
 * Makes a HTTP POST request for authentication.
 *
 * @param emailUserName the name of the user
 * @param password the password of the user
 * @param loginTokenOfCaptcha CAPTCHA token (Optional)
 * @param loginCaptchaAnswer answer of CAPTCHA token (Optional)
 * @return http response as a String//  w w w.j  av a2s.  com
 * @throws IOException
 */
// TODO: Refactor requestAuthentication() utilizing HttpPost.
private static String requestAuthentication(String emailUserName, String password, String loginTokenOfCaptcha,
        String loginCaptchaAnswer) throws IOException {

    // Prepare connection.
    URL url = new URL(URL_GOOGLE_LOGIN);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches(false);
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
    logger.fine("url: " + url);

    // Form the POST params.
    StringBuilder params = new StringBuilder();
    params.append("Email=").append(emailUserName).append("&Passwd=").append(password)
            .append("&source=OSDE-01&service=ig&accountType=HOSTED_OR_GOOGLE");
    if (loginTokenOfCaptcha != null) {
        params.append("&logintoken=").append(loginTokenOfCaptcha);
    }
    if (loginCaptchaAnswer != null) {
        params.append("&logincaptcha=").append(loginCaptchaAnswer);
    }

    // Send POST via output stream.
    OutputStream outputStream = null;
    try {
        outputStream = urlConnection.getOutputStream();
        outputStream.write(params.toString().getBytes(IgHttpUtil.ENCODING));
        outputStream.flush();
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }

    // Retrieve response.
    // TODO: Should the caller of this method need to know the responseCode?
    int responseCode = urlConnection.getResponseCode();
    logger.fine("responseCode: " + responseCode);
    InputStream inputStream = (responseCode == HttpURLConnection.HTTP_OK) ? urlConnection.getInputStream()
            : urlConnection.getErrorStream();

    logger.fine("inputStream: " + inputStream);
    try {
        String response = IOUtils.toString(inputStream, IgHttpUtil.ENCODING);
        return response;
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
}

From source file:com.navercorp.volleyextensions.volleyer.multipart.stack.MultipartHurlStack.java

@SuppressWarnings("deprecation")
/* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST:
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            // Prepare output. There is no need to set Content-Length explicitly,
            // since this is handled by HttpURLConnection using the size of the prepared
            // output stream.
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(postBody);//from  www  .jav a 2  s.c  om
            out.close();
        }
        break;
    case Method.GET:
        // Not necessary to set the request method because connection defaults to GET but
        // being explicit here.
        connection.setRequestMethod("GET");
        break;
    case Method.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case Method.POST:
        connection.setRequestMethod("POST");
        addMultipartIfExists(connection, request);
        break;
    case Method.PUT:
        connection.setRequestMethod("PUT");
        addMultipartIfExists(connection, request);
        break;
    case Method.HEAD:
        connection.setRequestMethod("HEAD");
        break;
    case Method.OPTIONS:
        connection.setRequestMethod("OPTIONS");
        break;
    case Method.TRACE:
        connection.setRequestMethod("TRACE");
        break;
    case Method.PATCH:
        connection.setRequestMethod("PATCH");
        addMultipartIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:com.googlecode.jmxtrans.model.output.support.HttpOutputWriter.java

private void writeResults(Server server, Query query, Iterable<Result> results,
        HttpURLConnection httpURLConnection) throws IOException {
    Closer closer = Closer.create();/*  www. ja v  a2s .  c o  m*/
    try {
        OutputStreamWriter outputStream = closer
                .register(new OutputStreamWriter(httpURLConnection.getOutputStream(), charset));

        target.write(outputStream, server, query, results);
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:com.spotify.helios.system.APITest.java

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);//from w  w w .j  a va 2 s .  c o m
    connection.setDoOutput(true);
    connection.getOutputStream().write(body);
    return connection;
}

From source file:io.mingle.v1.Connection.java

public Response run(String comprehension) {
    String expr = "{ \"query\": \"" + comprehension + "\", \"limit\": 10000 }";
    try {/*  ww w . j  a v a 2 s .  c om*/
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.connect();

        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        out.write(expr, 0, expr.length());
        out.flush();
        out.close();

        InputStream in = conn.getInputStream();
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        byte[] chunk = new byte[4096];
        int read = 0;
        while ((read = in.read(chunk)) > 0) {
            buf.write(chunk, 0, read);
        }
        in.close();

        String str = buf.toString();
        System.out.println("GOT JSON: " + str);
        return new Response(JSONValue.parse(str));
    } catch (Exception e) {
        System.err.printf("failed to execute: %s\n", expr);
        e.printStackTrace();
    }

    return null;
}

From source file:com.twotoasters.android.hoot.HootTransportHttpUrlConnection.java

private void setRequestData(HootRequest request, HttpURLConnection connection) throws IOException {
    OutputStream os = null;/*  w ww.ja va  2s .c  om*/
    try {
        os = new BufferedOutputStream(connection.getOutputStream());
        IOUtils.copy(request.getData(), os);
    } finally {
        if (os != null) {
            try {
                os.flush();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}