Example usage for java.net HttpURLConnection setRequestProperty

List of usage examples for java.net HttpURLConnection setRequestProperty

Introduction

In this page you can find the example usage for java.net HttpURLConnection setRequestProperty.

Prototype

public void setRequestProperty(String key, String value) 

Source Link

Document

Sets the general request property.

Usage

From source file:com.evrythng.java.wrapper.util.FileUtils.java

private static HttpURLConnection getConnectionForPrivateUpload(final URL url, final String contentType)
        throws IOException {

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpPut.METHOD_NAME);

    connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, contentType);
    connection.setRequestProperty(X_AMZ_ACL_HEADER_NAME, X_AMZ_ACL_HEADER_VALUE_PRIVATE);
    connection.setDoOutput(true);/*from   ww  w .j a v a2  s.  c  o  m*/
    connection.connect();
    return connection;
}

From source file:com.adanac.module.blog.api.HttpApiHelper.java

public static void baiduPush(int remain) {
    String pushUrl = DaoFactory.getDao(HtmlPageDao.class).findPushUrl();
    if (pushUrl == null) {
        if (logger.isInfoEnabled()) {
            logger.info("all html page has been pushed!");
        }/*from   ww  w . ja  va 2s.  c o  m*/
        return;
    }
    if (remain <= 0) {
        if (logger.isInfoEnabled()) {
            logger.info("there has no remain[" + remain + "]!");
        }
        return;
    }
    if (logger.isInfoEnabled()) {
        logger.info("find push url : " + pushUrl);
    }
    String url = "http://data.zz.baidu.com/urls?site=" + site + "&token=" + token;
    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/plain");
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(pushUrl.getBytes("UTF-8"));
        outputStream.write("\r\n".getBytes("UTF-8"));
        outputStream.flush();
        int status = connection.getResponseCode();
        if (logger.isInfoEnabled()) {
            logger.info("baidu-push response code : " + status);
        }
        if (status == HttpServletResponse.SC_OK) {
            String response = IOUtil.read(connection.getInputStream());
            if (logger.isInfoEnabled()) {
                logger.info("baidu-push response : " + response);
            }
            JSONObject result = JSONObject.fromObject(response);
            if (result.getInt("success") >= 1) {
                DaoFactory.getDao(HtmlPageDao.class).updateIsPush(pushUrl);
            } else {
                logger.warn("push url failed : " + pushUrl);
            }
            baiduPush(result.getInt("remain"));
        } else {
            logger.error("baidu-push error : " + IOUtil.read(connection.getErrorStream()));
        }
    } catch (Exception e) {
        logger.error("baidu push failed ...", e);
    }
}

From source file:com.gallatinsystems.common.util.S3Util.java

public static String getObjectAcl(String bucketName, String objectKey, String awsAccessId, String awsSecretKey)
        throws IOException {

    final String date = getDate();
    final URL url = new URL(String.format(S3_URL, bucketName, objectKey) + "?acl");
    final String payload = String.format(GET_PAYLOAD_ACL, date, bucketName, objectKey);
    final String signature = MD5Util.generateHMAC(payload, awsSecretKey);

    InputStream in = null;/*w ww .  jav  a 2s . c o  m*/
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Date", date);
        conn.setRequestProperty("Authorization", "AWS " + awsAccessId + ":" + signature);

        in = new BufferedInputStream(conn.getInputStream());

        return IOUtils.toString(in);
    } catch (Exception e) {
        log.log(Level.SEVERE, "Error getting ACL for : " + url.toString(), e);
        return null;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
        IOUtils.closeQuietly(in);
    }
}

From source file:core.Utility.java

public static ArrayList<String> getWikiText(String _word) throws MalformedURLException, IOException {
    ArrayList<String> _list = new ArrayList();
    try {/*from  w ww.  jav  a  2s. c  o  m*/

        URL url = new URL("http://en.wiktionary.org/w/api.php" + "?action=parse" + "&prop=wikitext" + "&page="
                + _word + "&format=xmlfm");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

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

        String output, wikiText = "";
        while ((output = br.readLine()) != null) {
            wikiText += output + "\n";
        }

        conn.disconnect();

    } catch (MalformedURLException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    }
    return _list;
}

From source file:localSPs.SpiderOakAPI.java

public static String connectWithREST(String url, String method)
        throws IOException, ProtocolException, MalformedURLException {
    String newURL = "";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    // Connect with a REST Method: GET, DELETE, PUT
    con.setRequestMethod(method);//from  www.  j a  va 2s.  c o m
    //add request header
    con.setReadTimeout(20000);
    con.setConnectTimeout(20000);
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    if (method.equals(DELETE) || method.equals(PUT))
        con.addRequestProperty("Authorization", "Base M5XWW5JNONZWUMSANBXXI3LBNFWC4Y3PNU5E2NDSNFXTEMZVJ5QWW");

    int responseCode = con.getResponseCode();
    // Read response
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    newURL = response.toString();
    return newURL;
}

From source file:ca.xecure.easychip.CommonUtilities.java

public static void http_post(String endpoint, Map<String, String> params) throws IOException {
    URL url;/*from w  w  w .jav  a2 s  .  co m*/
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }

    String body = JSONValue.toJSONString(params);
    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", "application/json");

        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();

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

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

    try {/* ww  w. j  a  v a  2 s  .c om*/
        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:net.daporkchop.porkselfbot.util.HTTPUtils.java

/**
 * Performs a POST request to the specified URL and returns the result.
 * <p />/*from   ww  w. ja v  a2 s  .co m*/
 * 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(final URL url, final String post, final String contentType)
        throws IOException {
    Validate.notNull(url);
    Validate.notNull(post);
    Validate.notNull(contentType);
    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);
    }

    InputStream inputStream = null;
    try {
        inputStream = connection.getInputStream();
        final String result = IOUtils.toString(inputStream, Charsets.UTF_8);
        return result;
    } catch (final IOException e) {
        IOUtils.closeQuietly(inputStream);
        inputStream = connection.getErrorStream();

        if (inputStream != null) {
            final String result = IOUtils.toString(inputStream, Charsets.UTF_8);
            return result;
        } else {
            throw e;
        }
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:be.roots.taconic.pricingguide.util.HttpUtil.java

private static HttpURLConnection getInputStreamFor(String urlAsString, String userName, String password)
        throws IOException {
    LOGGER.info(// w w  w  . ja v a 2s  .  c  o m
            REQUEST_METHOD + "ting data from url: " + urlAsString + " with timeout set to " + CONNECT_TIMEOUT);

    final URL url = new URL(urlAsString);
    final HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod(REQUEST_METHOD);
    con.setConnectTimeout(CONNECT_TIMEOUT);

    if (userName != null || password != null) {
        final String encoded = Base64.encode(userName + ":" + password);
        con.setRequestProperty("Authorization", "Basic " + encoded);
    }

    final int responseCode = con.getResponseCode();

    LOGGER.info("Response code: " + responseCode);
    return con;
}

From source file:net.daporkchop.porkselfbot.util.HTTPUtils.java

/**
 * Performs a POST request to the specified URL and returns the result.
 * <p />//from  w w  w.  j ava  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 performPostRequestWithAuth(final URL url, final String post, final String contentType,
        final String auth) throws IOException {
    Validate.notNull(url);
    Validate.notNull(post);
    Validate.notNull(contentType);
    final HttpURLConnection connection = createUrlConnection(url);
    final byte[] postAsBytes = post.getBytes(Charsets.UTF_8);

    connection.setRequestProperty("Authorization", auth);
    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);
    }

    InputStream inputStream = null;
    try {
        inputStream = connection.getInputStream();
        final String result = IOUtils.toString(inputStream, Charsets.UTF_8);
        return result;
    } catch (final IOException e) {
        IOUtils.closeQuietly(inputStream);
        inputStream = connection.getErrorStream();

        if (inputStream != null) {
            final String result = IOUtils.toString(inputStream, Charsets.UTF_8);
            return result;
        } else {
            throw e;
        }
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}