Example usage for java.net HttpURLConnection addRequestProperty

List of usage examples for java.net HttpURLConnection addRequestProperty

Introduction

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

Prototype

public void addRequestProperty(String key, String value) 

Source Link

Document

Adds a general request property specified by a key-value pair.

Usage

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

/**
 * Adds request properties to an HttpURLConnection.
 * @param connection//from w w  w.jav  a  2 s  . com
 * @param requestProperties
 */
private static void addRequestProperties(final HttpURLConnection connection,
        final RequestProperty[] requestProperties) {
    if (requestProperties != null) {
        for (RequestProperty requestProperty : requestProperties) {
            connection.addRequestProperty(requestProperty.getKey(), requestProperty.getValue());
        }
    }
}

From source file:com.nxt.zyl.data.volley.toolbox.HurlStack.java

private static void addBodyIfExists(HttpURLConnection connection, final Request<?> request)
        throws IOException, AuthFailureError {
    connection.setDoOutput(true);/*from   ww  w .  ja va  2 s.  c  om*/
    connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());

    if (request instanceof MultiPartRequest) {
        final UploadMultipartEntity multipartEntity = ((MultiPartRequest<?>) request).getMultipartEntity();
        // 
        connection.setFixedLengthStreamingMode((int) multipartEntity.getContentLength());
        multipartEntity.writeTo(connection.getOutputStream());
    } else {
        byte[] body = request.getBody();
        if (body != null) {
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(body);
            out.close();
        }
    }
}

From source file:ai.eve.volley.stack.HurlStack.java

private static void addBodyIfExists(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    connection.setDoOutput(true);/*w  w  w .  ja v a  2s  .  c  o  m*/
    connection.setRequestProperty("connection", "Keep-Alive");
    connection.addRequestProperty(HTTP.CONTENT_TYPE, request.getBodyContentType());
    request.getBody(connection);
}

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

public static InputStream getUrl(String urlString, String username, String password) {
    URL url = null;/*  w  ww  . j a va 2s.  co  m*/
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    }
    InputStream is = null;
    HttpURLConnection httpConnection;
    try {
        httpConnection = (HttpURLConnection) url.openConnection();

        setupAuthorization(httpConnection, username, password);

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

        is = httpConnection.getInputStream();

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

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.  ja v  a2 s.c o m
        connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(body);
    }
}

From source file:io.github.bonigarcia.wdm.Downloader.java

private static HttpURLConnection getConnection(URL url) throws IOException {
    Proxy proxy = createProxy();/*from   w  w w  .  j a va 2  s  .c o  m*/
    URLConnection conn1 = proxy != null ? url.openConnection(proxy) : url.openConnection();
    HttpURLConnection conn = (HttpURLConnection) conn1;
    conn.setRequestProperty("User-Agent", "Mozilla/5.0");
    conn.addRequestProperty("Connection", "keep-alive");
    conn.setInstanceFollowRedirects(true);
    HttpURLConnection.setFollowRedirects(true);
    conn.connect();
    return conn;
}

From source file:neal.http.impl.httpstack.HurlStack.java

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

From source file:com.android.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);/* w  w  w  .  j av  a2s.c o  m*/
        connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(body);
        out.close();
    }
}

From source file:com.illusionaryone.FrankerZAPIv1.java

@SuppressWarnings("UseSpecificCatch")
private static JSONObject readJsonFromUrl(String urlAddress) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    URL urlRaw;/*w  w w.  j a v  a2s.c o m*/
    HttpURLConnection urlConn;
    String jsonText = "";

    try {
        urlRaw = new URL(urlAddress);
        urlConn = (HttpURLConnection) urlRaw.openConnection();
        urlConn.setDoInput(true);
        urlConn.setRequestMethod("GET");
        urlConn.addRequestProperty("Content-Type", "application/json");
        urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 "
                + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");
        urlConn.connect();

        if (urlConn.getResponseCode() == 200) {
            inputStream = urlConn.getInputStream();
        } else {
            inputStream = urlConn.getErrorStream();
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
        jsonText = readAll(rd);
        jsonResult = new JSONObject(jsonText);
        fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText);
    } catch (JSONException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText);
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (NullPointerException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (MalformedURLException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (SocketTimeoutException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (IOException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (Exception ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } finally {
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (IOException ex) {
                fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
                com.gmt2001.Console.err.printStackTrace(ex);
            }
    }

    return (jsonResult);
}

From source file:com.fastbootmobile.encore.api.common.HttpGet.java

/**
 * Downloads the data from the provided URL.
 * @param inUrl The URL to get from//from   w w  w.j a  v a  2s .c  o m
 * @param query The query field. '?' + query will be appended automatically, and the query data
 *              MUST be encoded properly.
 * @return A byte array of the data
 */
public static byte[] getBytes(String inUrl, String query, boolean cached)
        throws IOException, RateLimitException {
    final String formattedUrl = inUrl + (query.isEmpty() ? "" : ("?" + query));

    Log.d(TAG, "Formatted URL: " + formattedUrl);

    URL url = new URL(formattedUrl);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestProperty("User-Agent", "OmniMusic/1.0-dev (http://www.omnirom.org)");
    urlConnection.setUseCaches(cached);
    urlConnection.setInstanceFollowRedirects(true);
    int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
    urlConnection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
    try {
        final int status = urlConnection.getResponseCode();
        // MusicBrainz returns 503 Unavailable on rate limit errors. Parse the JSON anyway.
        if (status == HttpURLConnection.HTTP_OK) {
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            int contentLength = urlConnection.getContentLength();
            if (contentLength <= 0) {
                // No length? Let's allocate 100KB.
                contentLength = 100 * 1024;
            }
            ByteArrayBuffer bab = new ByteArrayBuffer(contentLength);
            BufferedInputStream bis = new BufferedInputStream(in);
            int character;

            while ((character = bis.read()) != -1) {
                bab.append(character);
            }
            return bab.toByteArray();
        } else if (status == HttpURLConnection.HTTP_NOT_FOUND) {
            // 404
            return new byte[] {};
        } else if (status == HttpURLConnection.HTTP_FORBIDDEN) {
            return new byte[] {};
        } else if (status == HttpURLConnection.HTTP_UNAVAILABLE) {
            throw new RateLimitException();
        } else if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == 307 /* HTTP/1.1 TEMPORARY REDIRECT */
                || status == HttpURLConnection.HTTP_SEE_OTHER) {
            // We've been redirected, follow the new URL
            final String followUrl = urlConnection.getHeaderField("Location");
            Log.e(TAG, "Redirected to: " + followUrl);
            return getBytes(followUrl, "", cached);
        } else {
            Log.e(TAG, "Error when fetching: " + formattedUrl + " (" + urlConnection.getResponseCode() + ")");
            return new byte[] {};
        }
    } finally {
        urlConnection.disconnect();
    }
}