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:com.google.wave.api.oauth.impl.OpenSocialHttpClient.java

/**
 * Executes a request and writes all data in the request's body to the
 * output stream./*www  .  j a v a2  s.  c  om*/
 *
 * @param method
 * @param url
 * @param body
 * @return Response message
 */
private OpenSocialHttpResponseMessage send(String method, OpenSocialUrl url, String contentType, String body)
        throws IOException {
    HttpURLConnection connection = null;
    try {
        connection = getConnection(method, url, contentType);
        if (body != null) {
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
            out.write(body);
            out.flush();
            out.close();
        }

        return new OpenSocialHttpResponseMessage(method, url, connection.getInputStream(),
                connection.getResponseCode());
    } catch (IOException e) {
        throw new IOException(
                "Container returned status " + connection.getResponseCode() + " \"" + e.getMessage() + "\"");
    }
}

From source file:javaapplication1.Prog.java

public void transferStuff(String obj, String user) throws MalformedURLException, IOException {

    URL object = new URL("http://localhost:8080/bankserver/users/" + user);
    HttpURLConnection con = (HttpURLConnection) object.openConnection();
    con.setDoOutput(true);/*from  w  ww. j a v a2 s  . c  om*/
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Accept", "application/json");
    con.setRequestMethod("PUT");
    OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
    wr.write(obj);
    wr.flush();
    wr.close();
    con.getInputStream();
}

From source file:org.runnerup.export.GoogleFitSynchronizer.java

private Status sendData(StringWriter w, String suffix, RequestMethod method) throws IOException {
    Status status = Status.ERROR;
    for (int attempts = 0; attempts < MAX_ATTEMPTS; attempts++) {
        HttpURLConnection connect = getHttpURLConnection(suffix, method);
        GZIPOutputStream gos = new GZIPOutputStream(connect.getOutputStream());
        gos.write(w.toString().getBytes());
        gos.flush();//from  w  w  w  . j  a  v a  2 s .  co m
        gos.close();

        int code = connect.getResponseCode();
        try {
            if (code == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                continue;
            } else if (code != HttpStatus.SC_OK) {
                Log.i(getName(), SyncHelper.parse(new GZIPInputStream(connect.getErrorStream())).toString());
                status = Status.ERROR;
                break;
            } else {
                Log.i(getName(), SyncHelper.parse(new GZIPInputStream(connect.getInputStream())).toString());
                status = Status.OK;
                break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            connect.disconnect();
        }
    }
    return status;
}

From source file:com.adyen.httpclient.HttpURLConnectionClient.java

/**
 * Does a POST request with raw body// ww w  . j  a  v a2 s  .co  m
 */
private String doPostRequest(HttpURLConnection httpConnection, String requestBody)
        throws IOException, HTTPClientException {
    String response = null;

    OutputStream outputStream = httpConnection.getOutputStream();
    outputStream.write(requestBody.getBytes());
    outputStream.flush();

    int responseCode = httpConnection.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_OK) {
        //Read the response from the error stream
        if (httpConnection.getErrorStream() != null) {
            response = getResponseBody(httpConnection.getErrorStream());
        }

        HTTPClientException httpClientException = new HTTPClientException(responseCode, "HTTP Exception",
                httpConnection.getHeaderFields(), response);

        throw httpClientException;
    }

    //InputStream is only available on successful requests >= 200 <400
    response = getResponseBody(httpConnection.getInputStream());

    // close the connection
    httpConnection.disconnect();

    return response;
}

From source file:com.gsoc.ijosa.liquidgalaxycontroller.PW.collection.JsonObjectRequest.java

/**
 * Helper method to make an HTTP request.
 * @param urlConnection The HTTP connection.
 *///ww  w  .ja v  a 2s .c o m
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();
}

From source file:com.writewreckedsoftware.ullr.networking.UpdateMarker.java

@Override
protected String doInBackground(String... arg0) {
    String json = arg0[0];/*from   ww  w . ja  v  a 2 s  .c om*/
    JSONObject obj = null;
    String id = "";
    try {
        obj = new JSONObject(json);
        id = obj.getString("_id");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    URL url = null;
    String resultText = "";
    try {
        url = new URL("http://ullr.herokuapp.com/markers/" + id);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Content-Type", "application/json");
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(json);
        out.close();
        InputStream response = connection.getInputStream();
        resultText = NetworkHelpers.getInstance(null).convertStreamToString(response);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    JSONObject result = null;
    try {
        result = new JSONObject(resultText);
        result.put("_id", id);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return result.toString();
}

From source file:com.yaozu.object.volley.toolbox.HurlStack.java

@SuppressWarnings("deprecation")
/* package */static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, 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);/*from w  w w .j av  a2  s  . co m*/
            out.close();
        }
        break;
    case Request.Method.GET:
        // Not necessary to set the request method because connection
        // defaults to GET but
        // being explicit here.
        connection.setRequestMethod("GET");
        break;
    case Request.Method.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case Request.Method.POST:
        connection.setRequestMethod("POST");
        addBodyIfExists(connection, request);
        break;
    case Request.Method.PUT:
        connection.setRequestMethod("PUT");
        addBodyIfExists(connection, request);
        break;
    case Request.Method.HEAD:
        connection.setRequestMethod("HEAD");
        break;
    case Request.Method.OPTIONS:
        connection.setRequestMethod("OPTIONS");
        break;
    case Request.Method.TRACE:
        connection.setRequestMethod("TRACE");
        break;
    case Request.Method.PATCH:
        connection.setRequestMethod("PATCH");
        addBodyIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:edu.isi.wings.util.oodt.CurationServiceAPI.java

private String query(String method, String op, Object... args) {
    String url = this.curatorurl + this.service + op;
    try {/*from   w  w  w  . j  av a  2 s  .  c  o  m*/
        String params = "policy=" + URLEncoder.encode(this.policy, "UTF-8");
        for (int i = 0; i < args.length; i += 2) {
            params += "&" + args[i] + "=" + URLEncoder.encode(args[i + 1].toString(), "UTF-8");
        }

        URL urlobj = new URL(url);
        if ("GET".equals(method))
            urlobj = new URL(url + "?" + params);
        HttpURLConnection con = (HttpURLConnection) urlobj.openConnection();
        con.setRequestMethod(method);
        if (!"GET".equals(method)) {
            con.setDoOutput(true);
            DataOutputStream out = new DataOutputStream(con.getOutputStream());
            out.writeBytes(params);
            out.flush();
            out.close();
        }

        String result = IOUtils.toString(con.getInputStream());
        con.disconnect();
        return result;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

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

@Override
public final synchronized String dispatchPost(URI address, FormBuilder form)
        throws IOException, URISyntaxException {
    HttpURLConnection connection = prepareConnection(address, true, "POST");
    if (!Strings.isNullOrEmpty(form.getContentType())) {
        connection.setRequestProperty("Content-Type", form.getContentType());
    }//from  ww w. j a  va  2 s .c  om
    connection.connect();
    connection.getOutputStream().write(form.getBytes());
    if (connection.getResponseCode() != 200) {
        throw new IllegalStateException("Statuscode " + connection.getResponseCode() + " not supported");
    }

    String response = IOUtils.toString(connection.getInputStream());

    setCookie(connection);

    if (!isStartup) {
        return response;
    }
    return setupAuthentication(response);
}

From source file:com.hackerati.android.user_sdk.volley.HHurlStack.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);//from  w w  w  . java  2s.  com
            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:
        addBodyIfExists(connection, request);
        connection.setRequestMethod("PATCH");
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}