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:edu.gmu.csiss.automation.pacs.utils.BaseTool.java

/**
 * send a HTTP POST request/*from w w w.  j ava2  s  . c  om*/
 * @param param
 * @param input_url
 * @return
 */
public static String POST(String param, String input_url) {
    try {
        URL url = new URL(input_url);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/xml");
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);

        PrintWriter xmlOut = new PrintWriter(con.getOutputStream());
        xmlOut.write(param);
        xmlOut.flush();
        BufferedReader response = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String result = "";
        String line;
        while ((line = response.readLine()) != null) {
            result += "\n" + line;
        }
        return result.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.iflytek.android.framework.volley.toolbox.HurlStack.java

private static void addBodyIfExists(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
        connection.setDoOutput(true);/*www. j av  a2  s. c o  m*/
        VolleyLog.e("======3:" + request.getBodyContentType());
        connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(body);
        out.close();
    }
}

From source file:com.tohours.imo.util.TohoursUtils.java

/**
 * //w  w w .  j  ava 2  s. c  o m
 * @param path
 * @param charsetName
 * @param param
 * @return
 * @throws IOException
 */
public static String httpPost(String path, String param, String charsetName) throws IOException {
    String rv = null;
    URL url = null;
    HttpURLConnection conn = null;
    InputStream input = null;
    try {
        url = new URL(path);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "plain/text");
        conn.setRequestProperty("User-Agent", "Tohours Shake Project");
        OutputStream os = conn.getOutputStream();
        os.write(param.getBytes(charsetName));
        os.flush();
        os.close();
        input = conn.getInputStream();
        rv = TohoursUtils.inputStream2String(input, charsetName);
    } finally {
        if (input != null) {
            input.close();
        }
    }
    return rv;
}

From source file:com.ant.myteam.gcm.POST2GCM.java

public static void post(String apiKey, Content content) {

    try {/*  ww w  .j a v a  2s  .  c  o  m*/

        // 1. URL
        URL url = new URL("https://android.googleapis.com/gcm/send");

        // 2. Open connection
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 3. Specify POST method
        conn.setRequestMethod("POST");

        // 4. Set the headers
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key=" + apiKey);

        conn.setDoOutput(true);

        // 5. Add JSON data into POST request body

        //`5.1 Use Jackson object mapper to convert Contnet object into JSON
        ObjectMapper mapper = new ObjectMapper();

        // 5.2 Get connection output stream
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

        // 5.3 Copy Content "JSON" into
        mapper.writeValue(wr, content);

        // 5.4 Send the request
        wr.flush();

        // 5.5 close
        wr.close();

        // 6. Get the response
        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // 7. Print result
        System.out.println(response.toString());

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:pushandroid.POST2GCM.java

public static void post(Content content) {

    try {// ww  w.  j  av  a2 s.  c  om

        // 1. URL
        URL url = new URL(URL);

        // 2. Open connection
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 3. Specify POST method
        conn.setRequestMethod("POST");

        // 4. Set the headers
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key=" + apiKey);

        conn.setDoOutput(true);

        // 5. Add JSON data into POST request body
        //`5.1 Use Jackson object mapper to convert Contnet object into JSON
        ObjectMapper mapper = new ObjectMapper();

        // 5.2 Get connection output stream
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

        // 5.3 Copy Content "JSON" into
        mapper.writeValue(wr, content);

        // 5.4 Send the request
        wr.flush();

        // 5.5 close
        wr.close();

        // 6. Get the response
        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // 7. Print result
        System.out.println(response.toString());

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.denimgroup.threadfix.service.defects.RestUtils.java

public static InputStream postUrl(String urlString, String data, String username, String password) {
    URL url = null;//w  ww  .j  a  v a 2  s . c  om
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        log.warn("URL used for POST was bad: '" + urlString + "'");
        return null;
    }

    HttpURLConnection httpConnection = null;
    OutputStreamWriter outputWriter = null;
    try {
        httpConnection = (HttpURLConnection) url.openConnection();

        setupAuthorization(httpConnection, username, password);

        httpConnection.addRequestProperty("Content-Type", "application/json");
        httpConnection.addRequestProperty("Accept", "application/json");

        httpConnection.setDoOutput(true);
        outputWriter = new OutputStreamWriter(httpConnection.getOutputStream());
        outputWriter.write(data);
        outputWriter.flush();

        InputStream is = httpConnection.getInputStream();

        return is;
    } catch (IOException e) {
        log.warn("IOException encountered trying to post to URL with message: " + e.getMessage());
        if (httpConnection == null) {
            log.warn(
                    "HTTP connection was null so we cannot do further debugging of why the HTTP request failed");
        } else {
            try {
                InputStream errorStream = httpConnection.getErrorStream();
                if (errorStream == null) {
                    log.warn("Error stream from HTTP connection was null");
                } else {
                    log.warn(
                            "Error stream from HTTP connection was not null. Attempting to get response text.");
                    String postErrorResponse = IOUtils.toString(errorStream);
                    log.warn("Error text in response was '" + postErrorResponse + "'");
                }
            } catch (IOException e2) {
                log.warn("IOException encountered trying to read the reason for the previous IOException: "
                        + e2.getMessage(), e2);
            }
        }
    } finally {
        if (outputWriter != null) {
            try {
                outputWriter.close();
            } catch (IOException e) {
                log.warn("Failed to close output stream in postUrl.", e);
            }
        }
    }

    return null;
}

From source file:common.net.volley.toolbox.HurlStack.java

private static void addBodyIfExists(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {

    // before preConnect

    byte[] body = request.getBody();
    if (body != null) {
        stethoManager.preConnect(connection, new ByteArrayRequestEntity(request.getBody()));

        connection.setDoOutput(true);/* w  w w  .j a  v a  2  s .  c o m*/
        connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());

        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(body);
        out.close();

    }
}

From source file:Main.java

/**
 * Executes a post request using {@link HttpURLConnection}.
 *
 * @param url The request URL.//from ww w  .j a va 2s  .c  o m
 * @param data The request body, or null.
 * @param requestProperties Request properties, or null.
 * @return The response body.
 * @throws IOException If an error occurred making the request.
 */
// TODO: Remove this and use HttpDataSource once DataSpec supports inclusion of a POST body.
public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties)
        throws IOException {
    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(data != null);
        urlConnection.setDoInput(true);
        if (requestProperties != null) {
            for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) {
                urlConnection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue());
            }
        }
        // Write the request body, if there is one.
        if (data != null) {
            OutputStream out = urlConnection.getOutputStream();
            try {
                out.write(data);
            } finally {
                out.close();
            }
        }
        // Read and return the response body.
        InputStream inputStream = urlConnection.getInputStream();
        try {
            return toByteArray(inputStream);
        } finally {
            inputStream.close();
        }
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:com.memetix.mst.MicrosoftTranslatorAPI.java

/**
 * Gets the OAuth access token./*www .  j  a  v  a  2  s.com*/
 * @param clientId The Client key.
 * @param clientSecret The Client Secret
 */
public static String getToken(final String clientId, final String clientSecret) throws Exception {
    final String params = "grant_type=client_credentials&scope=http://api.microsofttranslator.com"
            + "&client_id=" + URLEncoder.encode(clientId, ENCODING) + "&client_secret="
            + URLEncoder.encode(clientSecret, ENCODING);

    final URL url = new URL(DatamarketAccessUri);
    final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
    if (referrer != null)
        uc.setRequestProperty("referer", referrer);
    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + ENCODING);
    uc.setRequestProperty("Accept-Charset", ENCODING);
    uc.setRequestMethod("POST");
    uc.setDoOutput(true);

    OutputStreamWriter wr = new OutputStreamWriter(uc.getOutputStream());
    wr.write(params);
    wr.flush();

    try {
        final int responseCode = uc.getResponseCode();
        final String result = inputStreamToString(uc.getInputStream());
        if (responseCode != 200) {
            throw new Exception("Error from Microsoft Translator API: " + result);
        }
        return result;
    } finally {
        if (uc != null) {
            uc.disconnect();
        }
    }
}

From source file:de.mas.telegramircbot.utils.images.ImgurUploader.java

public static String uploadImageAndGetLink(String clientID, byte[] image) throws IOException {
    URL url;/*from ww  w . ja  v a2 s  .c om*/
    url = new URL(Settings.IMGUR_API_URL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    String dataImage = Base64.getEncoder().encodeToString(image);
    String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(dataImage, "UTF-8");

    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Client-ID " + clientID);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    conn.connect();
    StringBuilder stb = new StringBuilder();
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        stb.append(line).append("\n");
    }
    wr.close();
    rd.close();

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(ImgurResponse.class, new ImgurResponseDeserializer());
    Gson gson = gsonBuilder.create();

    // The JSON data
    try {
        ImgurResponse response = gson.fromJson(stb.toString(), ImgurResponse.class);
        return response.getLink();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return stb.toString();
}