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:net.daporkchop.porkbot.util.HTTPUtils.java

/**
 * Performs a POST request to the specified URL and returns the result.
 * <p/>/*from   w ww.j  av  a  2  s.com*/
 * The POST data will be encoded in UTF-8 as the specified contentType. The response will be parsed as UTF-8.
 * If the server returns an error but still provides a body, the body will be returned as normal.
 * If the server returns an error without any body, a relevant {@link java.io.IOException} will be thrown.
 *
 * @param url         URL to submit the POST request to
 * @param post        POST data in the correct format to be submitted
 * @param contentType Content type of the POST data
 * @return Raw text response from the server
 * @throws IOException The request was not successful
 */
public static String performPostRequest(@NonNull URL url, @NonNull String post, @NonNull String contentType)
        throws IOException {
    final HttpURLConnection connection = createUrlConnection(url);
    final byte[] postAsBytes = post.getBytes(Charsets.UTF_8);

    connection.setRequestProperty("Content-Type", contentType + "; charset=utf-8");
    connection.setRequestProperty("Content-Length", "" + postAsBytes.length);
    connection.setDoOutput(true);

    OutputStream outputStream = null;
    try {
        outputStream = connection.getOutputStream();
        IOUtils.write(postAsBytes, outputStream);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }

    return sendRequest(connection);
}

From source file:Main.java

/**
 * Issue a POST request to the server.//from  ww w . j a va  2  s.co m
 *
 * @param endpoint
 *            POST address.
 * @param params
 *            request parameters.
 *
 * @throws java.io.IOException
 *             propagated from POST.
 */
public static String post(String endpoint, Map<String, String> params) throws IOException {
    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response
        int status = conn.getResponseCode();
        if (status != 200) {
            throw new IOException("Post failed with error code " + status);
        }

        // Get Response
        InputStream is = conn.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\n');
        }
        rd.close();
        return response.toString();

    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:Main.java

public static String simplePost(String url, Bundle params, String method)
        throws MalformedURLException, IOException {
    OutputStream os;/*from www  .j  a va  2 s.  co m*/

    System.setProperty("http.keepAlive", "false");
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " agent");

    conn.setRequestMethod(method);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    //conn.setRequestProperty("Connection", "Keep-Alive");

    conn.connect();

    os = new BufferedOutputStream(conn.getOutputStream());
    os.write(encodePostParams(params).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:core.RESTCalls.RESTPost.java

public static String httpPost(String urlStr, String[] paramName, String[] paramVal) throws Exception {

    URL url = new URL(urlStr);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");

    conn.setDoOutput(true);/*  www  . java  2  s.  c om*/
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setAllowUserInteraction(false);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    OutputStream out = conn.getOutputStream();

    Writer writer = new OutputStreamWriter(out, "UTF-8");

    for (int i = 0; i < paramName.length; i++) {

        writer.write(paramName[i]);
        writer.write("=");
        writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
        writer.write("&");
    }

    writer.close();
    out.close();

    if (conn.getResponseCode() != 200)
        throw new IOException(conn.getResponseMessage());

    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    StringBuilder sb = new StringBuilder();

    String line;

    while ((line = rd.readLine()) != null)
        sb.append(line + "\n");

    rd.close();

    conn.disconnect();

    return sb.toString();
}

From source file:com.playbasis.android.playbasissdk.http.toolbox.HurlStack.java

private static void addBodyIfExists(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
        connection.setDoOutput(true);//from ww  w  .  j a  v  a  2  s .co m
        connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(body);
    }
}

From source file:ly.stealth.punxsutawney.Marathon.java

private static JSONObject sendRequest(String uri, String method, JSONObject json) throws IOException {
    URL url = new URL(Marathon.url + uri);
    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    try {/*  ww w .j  ava  2  s  .  c  o m*/
        c.setRequestMethod(method);

        if (method.equalsIgnoreCase("POST")) {
            byte[] body = json.toString().getBytes("utf-8");
            c.setDoOutput(true);
            c.setRequestProperty("Content-Type", "application/json");
            c.setRequestProperty("Content-Length", "" + body.length);
            c.getOutputStream().write(body);
        }

        return (JSONObject) JSONValue.parse(new InputStreamReader(c.getInputStream(), "utf-8"));
    } catch (IOException e) {
        if (c.getResponseCode() == 404 && method.equals("GET"))
            return null;

        ByteArrayOutputStream response = new ByteArrayOutputStream();
        InputStream err = c.getErrorStream();
        if (err == null)
            throw e;

        Util.copyAndClose(err, response);
        IOException ne = new IOException(e.getMessage() + ": " + response.toString("utf-8"));
        ne.setStackTrace(e.getStackTrace());
        throw ne;
    } finally {
        c.disconnect();
    }
}

From source file:com.google.android.gcm.demo.app.ServerUtilities.java

/**
 * Issue a POST request to the server.//from   ww w . j a  v a  2  s  . co m
 *
 * @param endpoint POST address.
 * @param params request parameters.
 *
 * @throws IOException propagated from POST.
 */
private static void post(String endpoint, Map<String, String> params) throws IOException {
    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    JSONObject jsonObj = new JSONObject(params);
    String body = jsonObj.toString();
    Log.v(TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response
        int status = conn.getResponseCode();
        if (status != 200) {
            throw new IOException("Post failed with error code " + status);
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.arthurpitman.common.HttpUtils.java

/**
 * Connects to an HTTP resource using the post method.
 * @param url the URL to connect to.//from w  ww. ja va 2s  .c  om
 * @param requestProperties optional request properties, <code>null</code> if not required.
 * @param postData the data to post.
 * @return the resulting {@link HttpURLConnection}.
 * @throws IOException
 */
public static HttpURLConnection connectPost(final String url, final RequestProperty[] requestProperties,
        final byte[] postData) throws IOException {
    // setup connection
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setRequestMethod(POST_METHOD);

    // send the post form
    connection.setFixedLengthStreamingMode(postData.length);
    addRequestProperties(connection, requestProperties);
    OutputStream outStream = connection.getOutputStream();
    outStream.write(postData);
    outStream.close();

    return connection;
}

From source file:yodlee.ysl.api.io.HTTP.java

public static String doPost(String url, String requestBody) throws IOException {
    String mn = "doIO(POST : " + url + ", " + requestBody + " )";
    System.out.println(fqcn + " :: " + mn);
    URL restURL = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("User-Agent", userAgent);
    //conn.setRequestProperty("Content-Type", contentTypeURLENCODED);
    conn.setRequestProperty("Content-Type", contentTypeJSON);
    conn.setDoOutput(true);/*from w  w w  . j  a  va  2  s  .co m*/
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(requestBody);
    wr.flush();
    wr.close();
    int responseCode = conn.getResponseCode();
    System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP POST' request");
    System.out.println(fqcn + " :: " + mn + " : " + "Response Code : " + responseCode);
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuilder jsonResponse = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        jsonResponse.append(inputLine);
    }
    in.close();
    System.out.println(fqcn + " :: " + mn + " : " + jsonResponse.toString());
    return new String(jsonResponse);
}

From source file:yodlee.ysl.api.io.HTTP.java

public static String doPutNew(String url, String param, Map<String, String> sessionTokens)
        throws IOException, URISyntaxException {
    String mn = "doIO(PUT :" + url + ", sessionTokens =  " + sessionTokens.toString() + " )";
    System.out.println(fqcn + " :: " + mn);
    //param=param.replace("\"", "%22").replace("{", "%7B").replace("}", "%7D").replace(",", "%2C").replace("[", "%5B").replace("]", "%5D").replace(":", "%3A").replace(" ", "+");
    String processedURL = url;//+"?MFAChallenge="+param;//"%7B%22loginForm%22%3A%7B%22formType%22%3A%22token%22%2C%22mfaTimeout%22%3A%2299380%22%2C%22row%22%3A%5B%7B%22id%22%3A%22token_row%22%2C%22label%22%3A%22Security+Key%22%2C%22form%22%3A%220001%22%2C%22fieldRowChoice%22%3A%220001%22%2C%22field%22%3A%5B%7B%22id%22%3A%22token%22%2C%22name%22%3A%22tokenValue%22%2C%22type%22%3A%22text%22%2C%22value%22%3A%22123456%22%2C%22isOptional%22%3Afalse%2C%22valueEditable%22%3Atrue%2C%22maxLength%22%3A%2210%22%7D%5D%7D%5D%7D%7D";
    URL myURL = new URL(processedURL);
    System.out.println(fqcn + " :: " + mn + ": Request URL=" + processedURL.toString());
    HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
    conn.setRequestMethod("PUT");
    conn.setRequestProperty("Accept-Charset", "UTF-8");
    conn.setRequestProperty("Content-Type", contentTypeJSON);
    conn.setRequestProperty("Authorization", sessionTokens.toString());
    conn.setDoOutput(true);/*from   w ww .jav a 2  s. c o  m*/
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(param);
    wr.flush();
    wr.close();
    System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP PUT' request");
    int responseCode = conn.getResponseCode();
    System.out.println(fqcn + " :: " + mn + " : " + "Response Code : " + responseCode);
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuilder jsonResponse = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
        jsonResponse.append(inputLine);
    }
    in.close();
    System.out.println(fqcn + " :: " + mn + " : " + jsonResponse.toString());
    return new String(jsonResponse);
}