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.gallatinsystems.common.util.S3Util.java

public static boolean put(String bucketName, String objectKey, byte[] data, String contentType,
        boolean isPublic, String awsAccessId, String awsSecretKey) throws IOException {

    final byte[] md5Raw = MD5Util.md5(data);
    final String md5Base64 = Base64.encodeBase64String(md5Raw).trim();
    final String md5Hex = MD5Util.toHex(md5Raw);
    final String date = getDate();
    final String payloadStr = isPublic ? PUT_PAYLOAD_PUBLIC : PUT_PAYLOAD_PRIVATE;
    final String payload = String.format(payloadStr, md5Base64, contentType, date, bucketName, objectKey);
    final String signature = MD5Util.generateHMAC(payload, awsSecretKey);
    final URL url = new URL(String.format(S3_URL, bucketName, objectKey));

    OutputStream out = null;/* ww w.  j a v a  2 s  . com*/
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("PUT");
        conn.setRequestProperty("Content-MD5", md5Base64);
        conn.setRequestProperty("Content-Type", contentType);
        conn.setRequestProperty("Date", date);

        if (isPublic) {
            // If we don't send this header, the object will be private by default
            conn.setRequestProperty("x-amz-acl", "public-read");
        }

        conn.setRequestProperty("Authorization", "AWS " + awsAccessId + ":" + signature);

        out = new BufferedOutputStream(conn.getOutputStream());

        IOUtils.copy(new ByteArrayInputStream(data), out);
        out.flush();

        int status = conn.getResponseCode();
        if (status != 200 && status != 201) {
            log.severe("Error uploading file: " + url.toString());
            log.severe(IOUtils.toString(conn.getInputStream()));
            return false;
        }
        String etag = conn.getHeaderField("ETag");
        etag = etag != null ? etag.replaceAll("\"", "") : null;// Remove quotes
        if (!md5Hex.equals(etag)) {
            log.severe("ETag comparison failed. Response ETag: " + etag + "Locally computed MD5: " + md5Hex);
            return false;
        }
        return true;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
        IOUtils.closeQuietly(out);
    }
}

From source file:com.avinashbehera.sabera.network.HttpClient.java

public static JSONObject SendHttpPostUsingUrlConnection(String url, JSONObject jsonObjSend) {

    URL sendUrl;// w  w  w.j a va 2  s .c om
    try {
        sendUrl = new URL(url);
    } catch (MalformedURLException e) {
        Log.d(TAG, "SendHttpPostUsingUrlConnection malformed URL");
        return null;
    }

    HttpURLConnection conn = null;

    try {
        conn = (HttpURLConnection) sendUrl.openConnection();
        conn.setReadTimeout(15000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setChunkedStreamingMode(1024);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.addRequestProperty("Content-length", jsonObjSend.toJSONString().length() + "");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        //writer.write(getPostDataStringfromJsonObject(jsonObjSend));
        Log.d(TAG, "jsonobjectSend = " + jsonObjSend.toString());
        //writer.write(jsonObjSend.toString());
        writer.write(String.valueOf(jsonObjSend));

        writer.flush();
        writer.close();
        os.close();

        int responseCode = conn.getResponseCode();
        Log.d(TAG, "responseCode = " + responseCode);

        if (responseCode == HttpsURLConnection.HTTP_OK) {

            Log.d(TAG, "responseCode = HTTP OK");

            InputStream instream = conn.getInputStream();

            String resultString = convertStreamToString(instream);
            instream.close();
            Log.d(TAG, "resultString = " + resultString);
            //resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"

            // Transform the String into a JSONObject
            JSONParser parser = new JSONParser();
            JSONObject jsonObjRecv = (JSONObject) parser.parse(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");

            return jsonObjRecv;

        }

    } catch (Exception e) {
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return null;

}

From source file:crow.util.Util.java

public static String urlPost(HttpURLConnection conn, String encodePostParam) throws IOException {
    int responseCode = -1;
    OutputStream osw = null;/*  ww w. ja  va 2s.  com*/
    try {
        conn.setConnectTimeout(20000);
        conn.setReadTimeout(12000);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setDoOutput(true);
        byte[] bytes = encodePostParam.getBytes("UTF-8");
        conn.setRequestProperty("Content-Length", Integer.toString(bytes.length));
        osw = conn.getOutputStream();
        osw.write(bytes);
        osw.flush();
        responseCode = conn.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new IOException("");
        } else {
            String s = inputStreamToString(conn.getInputStream());
            return s;
        }
    } finally {
        try {
            if (osw != null)
                osw.close();
        } catch (Exception ignore) {
        }
    }
}

From source file:com.rutarget.UpsourceReviewStatsExtension.PageExtension.java

private static <T> T request(String method, @Nullable Object parameter, Class<T> clazz) throws IOException {
    String address = UPSOURCE_API_URL + method;
    URL url = new URL(address);
    @SuppressWarnings("ConstantConditions")
    HttpURLConnection c = (HttpURLConnection) (PROXY != null ? url.openConnection(PROXY)
            : url.openConnection());/* w ww  .  j av a2s  .  c o m*/
    String authString = UPSOURCE_USERNAME + ":" + UPSOURCE_PASSWORD;
    //Base64 doesn't look thread safe, therefore we create new instance for each occasion
    c.setRequestProperty("Authorization", "Basic " + new String(new Base64().encode(authString.getBytes())));

    if (parameter != null) {
        String output = GSON.toJson(parameter);
        c.setDoOutput(true);
        c.setRequestMethod("POST");
        c.setRequestProperty("Content-Type", "application/json");
        c.setRequestProperty("Content-Length", String.valueOf(output.length()));
        c.getOutputStream().write(output.getBytes("UTF-8"));
    }
    InputStream inputStream = c.getInputStream();
    String response = IOUtils.toString(inputStream);
    try {
        JsonObject element = (JsonObject) new JsonParser().parse(response);
        return GSON.fromJson(element.get("result"), clazz);
    } catch (Exception e) {
        throw new IOException(
                "Failed to parse response " + escapeToHtmlAttribute(response) + ": " + e.getMessage());
    }
}

From source file:io.jari.geenstijl.API.API.java

public static String postUrl(String url, List<NameValuePair> params, String cheader, boolean refererandorigin)
        throws IOException {
    HttpURLConnection http = (HttpURLConnection) new URL(url).openConnection();
    http.setRequestMethod("POST");
    http.setDoInput(true);/*from  w w w  .  j a  v  a2s  .co m*/
    http.setDoOutput(true);
    if (cheader != null)
        http.setRequestProperty("Cookie", cheader);
    if (refererandorigin) {
        http.setRequestProperty("Referer",
                "http://www.geenstijl.nl/mt/archieven/2014/01/brein_chanteert_ondertitelaars.html");
        http.setRequestProperty("Origin", "http://www.geenstijl.nl");
    }
    OutputStream os = http.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(getQuery(params));
    writer.flush();
    writer.close();
    os.close();

    http.connect();

    InputStream in = http.getInputStream();
    String encoding = http.getContentEncoding();
    encoding = encoding == null ? "UTF-8" : encoding;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buf = new byte[8192];
    int len = 0;
    while ((len = in.read(buf)) != -1) {
        baos.write(buf, 0, len);
    }
    return new String(baos.toByteArray(), encoding);
}

From source file:com.gson.util.HttpKit.java

/**
 * /*from   w  w w .j a  v a 2 s. c om*/
 * @param url
 * @param params
 * @param file
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws KeyManagementException
 */
public static String upload(String url, File file)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; // ?  
    StringBuffer bufferRes = null;
    URL urlGet = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("connection", "Keep-Alive");
    conn.setRequestProperty("user-agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36");
    conn.setRequestProperty("Charsert", "UTF-8");
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

    OutputStream out = new DataOutputStream(conn.getOutputStream());
    byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// ??  
    StringBuilder sb = new StringBuilder();
    sb.append("--");
    sb.append(BOUNDARY);
    sb.append("\r\n");
    sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + file.getName() + "\"\r\n");
    sb.append("Content-Type:application/octet-stream\r\n\r\n");
    byte[] data = sb.toString().getBytes();
    out.write(data);
    DataInputStream fs = new DataInputStream(new FileInputStream(file));
    int bytes = 0;
    byte[] bufferOut = new byte[1024];
    while ((bytes = fs.read(bufferOut)) != -1) {
        out.write(bufferOut, 0, bytes);
    }
    out.write("\r\n".getBytes()); //  
    fs.close();
    out.write(end_data);
    out.flush();
    out.close();

    // BufferedReader???URL?  
    InputStream in = conn.getInputStream();
    BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
    String valueString = null;
    bufferRes = new StringBuffer();
    while ((valueString = read.readLine()) != null) {
        bufferRes.append(valueString);
    }
    in.close();
    if (conn != null) {
        // 
        conn.disconnect();
    }
    return bufferRes.toString();
}

From source file:com.hichengdai.qlqq.front.util.HttpKit.java

/**
 * /*  ww w .  j av a  2 s  . co  m*/
 * 
 * @param url
 * @param params
 * @param file
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws KeyManagementException
 */
public static String upload(String url, File file)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; // ?
    StringBuffer bufferRes = null;
    URL urlGet = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("connection", "Keep-Alive");
    conn.setRequestProperty("user-agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36");
    conn.setRequestProperty("Charsert", "UTF-8");
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

    OutputStream out = new DataOutputStream(conn.getOutputStream());
    byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// ??
    StringBuilder sb = new StringBuilder();
    sb.append("--");
    sb.append(BOUNDARY);
    sb.append("\r\n");
    sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + file.getName() + "\"\r\n");
    sb.append("Content-Type:application/octet-stream\r\n\r\n");
    byte[] data = sb.toString().getBytes();
    out.write(data);
    DataInputStream fs = new DataInputStream(new FileInputStream(file));
    int bytes = 0;
    byte[] bufferOut = new byte[1024];
    while ((bytes = fs.read(bufferOut)) != -1) {
        out.write(bufferOut, 0, bytes);
    }
    out.write("\r\n".getBytes()); // 
    fs.close();
    out.write(end_data);
    out.flush();
    out.close();

    // BufferedReader???URL?
    InputStream in = conn.getInputStream();
    BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
    String valueString = null;
    bufferRes = new StringBuffer();
    while ((valueString = read.readLine()) != null) {
        bufferRes.append(valueString);
    }
    in.close();
    if (conn != null) {
        // 
        conn.disconnect();
    }
    return bufferRes.toString();
}

From source file:com.melniqw.instagramsdk.Network.java

private static String sendDummyRequest(String url, String body, Request request) throws IOException {
    HttpURLConnection connection = null;
    try {/* w w  w  .  j  a v  a  2  s  .  co  m*/
        connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(10000);
        connection.setUseCaches(false);
        connection.setDoInput(true);
        //            connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
        if (request == Request.GET) {
            connection.setDoOutput(false);
            connection.setRequestMethod("GET");
        } else if (request == Request.POST) {
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
        }
        if (REQUEST_ENABLE_COMPRESSION)
            connection.setRequestProperty("Accept-Encoding", "gzip");
        if (request == Request.POST)
            connection.getOutputStream().write(body.getBytes("utf-8"));
        int code = connection.getResponseCode();
        System.out.println(TAG + " responseCode = " + code);
        //It may happen due to keep-alive problem http://stackoverflow.com/questions/1440957/httpurlconnection-getresponsecode-returns-1-on-second-invocation
        if (code == -1)
            throw new WrongResponseCodeException("Network error");
        // ?    200
        //on error can also read error stream from connection.
        InputStream inputStream = new BufferedInputStream(connection.getInputStream(), 8192);
        String encoding = connection.getHeaderField("Content-Encoding");
        if (encoding != null && encoding.equalsIgnoreCase("gzip"))
            inputStream = new GZIPInputStream(inputStream);
        String response = Utils.convertStreamToString(inputStream);
        System.out.println(TAG + " response = " + response);
        return response;
    } finally {
        if (connection != null)
            connection.disconnect();
    }
}

From source file:net.mutil.util.HttpUtil.java

public static String connServerForResultPost(String strUrl, HashMap<String, String> entityMap)
        throws ClientProtocolException, IOException {
    String strResult = "";
    URL url = new URL(HttpUtil.getPCURL() + strUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    StringBuilder entitySb = new StringBuilder("");

    Object[] entityKeys = entityMap.keySet().toArray();
    for (int i = 0; i < entityKeys.length; i++) {
        String key = (String) entityKeys[i];
        if (i == 0) {
            entitySb.append(key + "=" + entityMap.get(key));
        } else {//w  w  w  .  j  a  va  2  s. c o m
            entitySb.append("&" + key + "=" + entityMap.get(key));
        }
    }
    byte[] entity = entitySb.toString().getBytes("UTF-8");
    System.out.println(url.toString() + entitySb.toString());
    conn.setConnectTimeout(5000);
    conn.setDoOutput(true);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
    conn.getOutputStream().write(entity);
    if (conn.getResponseCode() == 200) {
        InputStream inputstream = conn.getInputStream();
        StringBuffer buffer = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = inputstream.read(b)) != -1;) {
            buffer.append(new String(b, 0, n));
        }
        strResult = buffer.toString();
    }
    return strResult;
}

From source file:com.example.scandevice.MainActivity.java

public static String excutePost(String targetURL, String urlParameters) {
    URL url;// www. j a v a  2s .c  o m
    HttpURLConnection connection = null;
    try {
        //Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("charset", "utf-8");

        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

    } catch (Exception e) {
        e.printStackTrace();
        return "Don't post data";

    } finally {

        if (connection != null) {
            connection.disconnect();
        }
    }
    return "Data Sent";
}