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:Main.java

public static String customrequest(String url, HashMap<String, String> params, String method) {
    try {/*  w w  w .  j a  v  a  2s .c om*/

        URL postUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setConnectTimeout(5 * 1000);

        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");

        conn.connect();
        OutputStream out = conn.getOutputStream();
        StringBuilder sb = new StringBuilder();
        if (null != params) {
            int i = params.size();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (i == 1) {
                    sb.append(entry.getKey() + "=" + entry.getValue());
                } else {
                    sb.append(entry.getKey() + "=" + entry.getValue() + "&");
                }

                i--;
            }
        }
        String content = sb.toString();
        out.write(content.getBytes("UTF-8"));
        out.flush();
        out.close();
        InputStream inStream = conn.getInputStream();
        String result = inputStream2String(inStream);
        conn.disconnect();
        return result;
    } catch (Exception e) {
        // TODO: handle exception
    }
    return null;
}

From source file:Main.java

public static String upLoad(File file, String RequestURL) {
    String BOUNDER = UUID.randomUUID().toString();
    String PREFIX = "--";
    String END = "/r/n";

    try {//from w w  w .java2s  . c  o  m
        URL url = new URL(RequestURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(TIME_OUT);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Charset", CHARSET);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Cotent-Type", CONTENT_TYPE + ";boundary=" + BOUNDER);

        if (file != null) {
            OutputStream outputStream = connection.getOutputStream();

            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
            StringBuffer sb = new StringBuffer();
            sb.append(PREFIX);
            sb.append(BOUNDER + END);
            dataOutputStream.write(sb.toString().getBytes());
            InputStream in = new FileInputStream(file);
            byte[] b = new byte[1024];
            int l = 0;
            while ((l = in.read()) != -1) {
                outputStream.write(b, 0, l);
            }
            in.close();
            dataOutputStream.write(END.getBytes());
            dataOutputStream.write((PREFIX + BOUNDER + PREFIX + END).getBytes());
            dataOutputStream.flush();

            int i = connection.getResponseCode();
            if (i == 200) {
                return SUCCESS;
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    return FALIURE;

}

From source file:Main.java

public static String uploadFile(File file, String RequestURL) {
    String BOUNDARY = UUID.randomUUID().toString();
    String PREFIX = "--", LINE_END = "\r\n";
    String CONTENT_TYPE = "multipart/form-data";

    try {//from ww  w  . ja va 2s  . c o m
        URL url = new URL(RequestURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(TIME_OUT);
        conn.setConnectTimeout(TIME_OUT);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Charset", CHARSET);
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
        if (file != null) {

            OutputStream outputSteam = conn.getOutputStream();

            DataOutputStream dos = new DataOutputStream(outputSteam);
            StringBuffer sb = new StringBuffer();
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);

            sb.append("Content-Disposition: form-data; name=\"img\"; filename=\"" + file.getName() + "\""
                    + LINE_END);
            sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
            sb.append(LINE_END);
            dos.write(sb.toString().getBytes());
            InputStream is = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
            }
            is.close();
            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();

            int res = conn.getResponseCode();
            Log.e(TAG, "response code:" + res);
            if (res == 200) {
                return SUCCESS;
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return FAILURE;
}

From source file:export.FormCrawler.java

public static void postMulti(HttpURLConnection conn, Part<?> parts[]) throws IOException {
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
    for (int i = 0; i < parts.length; i++) {
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + parts[i].name + "\"");
        if (parts[i].filename != null)
            outputStream.writeBytes("; filename=\"" + parts[i].filename + "\"");
        outputStream.writeBytes(lineEnd);

        if (parts[i].contentType != null)
            outputStream.writeBytes("Content-Type: " + parts[i].contentType + lineEnd);
        if (parts[i].contentTransferEncoding != null)
            outputStream.writeBytes("Content-Transfer-Encoding: " + parts[i].contentTransferEncoding + lineEnd);
        outputStream.writeBytes(lineEnd);
        parts[i].value.write(outputStream);
        outputStream.writeBytes(lineEnd);
    }// ww w. j  av a2  s .c  o m
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    outputStream.flush();
    outputStream.close();
}

From source file:io.apiman.manager.test.es.ESMetricsAccessorTest.java

private static void loadTestData() throws Exception {
    String url = "http://localhost:6500/_bulk";
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod("POST");
    conn.setDoInput(true);/*  w w  w . ja v  a 2 s  . c o  m*/
    conn.setDoOutput(true);
    OutputStream os = conn.getOutputStream();
    InputStream is = ESMetricsAccessorTest.class.getResourceAsStream("bulk-metrics-data.txt");
    IOUtils.copy(is, os);
    IOUtils.closeQuietly(is);
    IOUtils.closeQuietly(os);
    if (conn.getResponseCode() > 299) {
        IOUtils.copy(conn.getInputStream(), System.err);
        throw new IOException("Bulk load of data failed with: " + conn.getResponseMessage());
    }

    client.execute(new Refresh.Builder().addIndex("apiman_metrics").refresh(true).build());
}

From source file:chen.android.toolkit.network.HttpConnection.java

/**
 * </br><b>title : </b>      ????POST??
 * </br><b>description :</b>????POST??
 * </br><b>time :</b>      2012-7-8 ?4:34:08
 * @param method         ??// w  ww  .  j a va  2s  .  c om
 * @param url            POSTURL
 * @param datas            ????
 * @return               ???
 * @throws IOException
 */
private static InputStream connect(String method, URL url, byte[]... datas) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod(method);
    conn.setUseCaches(false);
    conn.setInstanceFollowRedirects(true);
    conn.setConnectTimeout(6 * 1000);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Charset", "UTF-8");
    OutputStream outputStream = conn.getOutputStream();
    for (byte[] data : datas) {
        outputStream.write(data);
    }
    outputStream.close();
    return conn.getInputStream();
}

From source file:no.ntnu.wifimanager.ServerUtilities.java

/**
 * Issue a POST request to server./*from  w w  w  .j a  v a 2 s . c o m*/
 *
 * @param serverUrl POST address.
 * @param params request parameters.
 *
 * @throws IOException propagated from POST.
 */
public static void HTTPpost(String serverUrl, Map<String, String> params, String contentType)
        throws IOException {
    URL url;
    try {
        url = new URL(serverUrl);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + serverUrl);
    }
    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();
    Log.v(LOG_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", contentType);
        // 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:gov.nasa.arc.geocam.geocam.HttpPost.java

public static int post(String url, Map<String, String> vars, String fileKey, String fileName,
        InputStream istream, String username, String password) throws IOException {
    HttpURLConnection conn = createConnection(url, username, password);

    try {/*from   w  ww .  j a  v a2 s . co m*/
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

        Log.d("HttpPost", vars.toString());

        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        assembleMultipart(out, vars, fileKey, fileName, istream);
        istream.close();
        out.flush();

        InputStream in = conn.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in), 2048);

        // Set postedSuccess to true if there is a line in the HTTP response in
        // the form "GEOCAM_SHARE_POSTED <file>" where <file> equals fileName.
        // Our old success condition was just checking for HTTP return code 200; turns
        // out that sometimes gives false positives.
        Boolean postedSuccess = false;
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            //Log.d("HttpPost", line);
            if (!postedSuccess && line.contains("GEOCAM_SHARE_POSTED")) {
                String[] vals = line.trim().split("\\s+");
                for (int i = 0; i < vals.length; ++i) {
                    //String filePosted = vals[1];
                    if (vals[i].equals(fileName)) {
                        Log.d(GeoCamMobile.DEBUG_ID, line);
                        postedSuccess = true;
                        break;
                    }
                }
            }
        }
        out.close();

        int responseCode = 0;
        responseCode = conn.getResponseCode();
        if (responseCode == 200 && !postedSuccess) {
            // our code for when we got value 200 but no confirmation
            responseCode = -3;
        }
        return responseCode;
    } catch (UnsupportedEncodingException e) {
        throw new IOException("HttpPost - Encoding exception: " + e);
    }

    // ??? when would this ever be thrown?
    catch (IllegalStateException e) {
        throw new IOException("HttpPost - IllegalState: " + e);
    }

    catch (IOException e) {
        try {
            return conn.getResponseCode();
        } catch (IOException f) {
            throw new IOException("HttpPost - IOException: " + e);
        }
    }
}

From source file:io.helixservice.feature.configuration.cloudconfig.CloudConfigDecrypt.java

/**
 * Decrypt an encrypted string/*  w w w . jav a2  s.  c om*/
 * <p>
 * This method blocks on a HTTP request.
 *
 * @param name property or filename for reference/logging
 * @param encryptedValue Encrypted string
 * @param cloudConfigUri URI of the Cloud Config server
 * @param httpBasicHeader HTTP Basic header containing username and password for Cloud Config server
 * @return
 */
public static String decrypt(String name, String encryptedValue, String cloudConfigUri,
        String httpBasicHeader) {
    String result = encryptedValue;

    // Remove prefix if needed
    if (encryptedValue.startsWith(CIPHER_PREFIX)) {
        encryptedValue = encryptedValue.substring(CIPHER_PREFIX.length());
    }

    String decryptUrl = cloudConfigUri + "/decrypt";

    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(decryptUrl).openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);

        connection.setRequestMethod("POST");
        connection.addRequestProperty(AUTHORIZATION_HEADER, httpBasicHeader);
        connection.setRequestProperty("Content-Type", "text/plain");
        connection.setRequestProperty("Content-Length", Integer.toString(encryptedValue.getBytes().length));
        connection.setRequestProperty("Accept", "*/*");

        // Write body
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(encryptedValue.getBytes());
        outputStream.close();

        if (connection.getResponseCode() == 200) {
            InputStream inputStream = connection.getInputStream();
            result = IOUtils.toString(inputStream);
            inputStream.close();
        } else {
            LOG.error("Unable to Decrypt name=" + name + " due to httpStatusCode="
                    + connection.getResponseCode() + " for decryptUrl=" + decryptUrl);
        }
    } catch (IOException e) {
        LOG.error("Unable to connect to Cloud Config server at decryptUrl=" + decryptUrl, e);
    }

    return result;
}

From source file:Main.java

public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties)
        throws IOException {
    HttpURLConnection urlConnection = null;
    try {/*w w  w  . j  ava2s  .c o  m*/
        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());
            }
        }
        if (data != null) {
            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            out.write(data);
            out.close();
        }
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        return convertInputStreamToByteArray(in);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}