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.heliosdecompiler.helios.controller.UpdateController.java

public void doUpdate() {
    try {// ww w  .  j  a v  a  2s  .  c  o  m
        Version thisVersion = Version.valueOf(getVersion());

        URL url = new URL(UPDATE_URL);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.addRequestProperty("User-Agent", "Helios Standalone App");

        String changelog = null;
        Version latestVersion = null;

        if (urlConnection.getResponseCode() == 200) {
            try (InputStream updateStream = urlConnection.getInputStream()) {
                JsonObject jsonObject = GSON.fromJson(new InputStreamReader(updateStream, "UTF-8"),
                        JsonObject.class);
                JsonArray actions = jsonObject.get("actions").getAsJsonArray();
                for (JsonElement jsonElement : actions) {
                    JsonObject action = jsonElement.getAsJsonObject();
                    if (action.get("_class") != null) {
                        String actionClass = action.get("_class").getAsString();
                        if (actionClass.equals("hudson.plugins.release.SafeParametersAction")) {
                            JsonArray parameters = action.get("parameters").getAsJsonArray();
                            for (JsonElement jsonElement1 : parameters) {
                                JsonObject parameter = jsonElement1.getAsJsonObject();
                                if (parameter.get("name").getAsString().equals("CHANGELOG")) {
                                    changelog = parameter.get("value").getAsString();
                                } else if (parameter.get("name").getAsString().equals("RELEASE_VERSION")) {
                                    latestVersion = Version.valueOf(parameter.get("value").getAsString());
                                }
                            }
                        }
                    }
                }
            }
        }

        System.out.println("Latest version: " + latestVersion);
        System.out.println("Changelog: " + changelog);

        if (changelog != null && latestVersion != null) {
            if (latestVersion.greaterThan(thisVersion)) {
                messageHandler.prompt(Message.UPDATER_UPDATE_FOUND.format(latestVersion.toString(), changelog),
                        result -> {
                            if (result) {
                                String urlToUse = DOWNLOAD_URL;
                                String extensionToUse = ".jar";
                                if (OSUtils.getOS() == OSUtils.OS.WINDOWS) {
                                    urlToUse = DOWNLOAD_URL_WINDOWS;
                                    extensionToUse = ".exe";
                                } else if (OSUtils.getOS() == OSUtils.OS.MAC) {
                                    urlToUse = DOWNLOAD_URL_OSX;
                                    extensionToUse = ".dmg";
                                }

                                String downloadUrlStr = urlToUse;

                                File target = messageHandler.chooseFile()
                                        .withTitle(Message.UPDATER_SELECT_SAVE_LOCATION.format())
                                        .withExtensionFilter(
                                                new FileFilter(Message.FILETYPE_ANY.format(), extensionToUse),
                                                true)
                                        .promptSave();

                                if (target != null) {
                                    backgroundTaskHelper.submit(new BackgroundTask(
                                            Message.UPDATER_DOWNLOADING_HELIOS.format(), true, () -> {
                                                try {
                                                    URL downloadurl = new URL(downloadUrlStr);
                                                    HttpURLConnection downloadconnection = (HttpURLConnection) downloadurl
                                                            .openConnection();
                                                    downloadconnection.addRequestProperty("User-Agent",
                                                            "Helios Standalone App");
                                                    try (InputStream downloadStream = downloadconnection
                                                            .getInputStream();
                                                            FileOutputStream outputStream = new FileOutputStream(
                                                                    target)) {
                                                        IOUtils.copy(downloadStream, outputStream);
                                                    }

                                                    messageHandler.handleMessage(
                                                            Message.UPDATER_UPDATE_SUCCESSFUL.format());
                                                } catch (Throwable t) {
                                                    messageHandler.handleException(
                                                            Message.ERROR_UNEXPECTED_ERROR.format(
                                                                    Message.UPDATER_UPDATE_TASK_NAME.getText()),
                                                            t);
                                                }
                                            }));
                                }
                            }
                        });
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:org.myframe.http.HttpConnectStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());/*from w ww  .j  a v a  2s.com*/
    map.putAll(additionalHeaders);

    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);

    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());

    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            String value = "";
            for (String v : header.getValue()) {
                value += (v + "; ");
            }
            Header h = new BasicHeader(header.getKey(), value);
            response.addHeader(h);
        }
    }
    return response;
}

From source file:org.kymjs.kjframe.http.HttpConnectStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    //just marker by chenlin
    map.putAll(request.getHeaders());/*from   w  w w.  jav a 2s. c  om*/
    map.putAll(additionalHeaders);

    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {

        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);

    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());

    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            String value = "";
            for (String v : header.getValue()) {
                value += (v + "; ");
            }
            Header h = new BasicHeader(header.getKey(), value);
            response.addHeader(h);
        }
    }
    return response;
}

From source file:com.cloudera.nav.sdk.client.writer.MetadataWriterFactory.java

private HttpURLConnection createHttpStream() throws IOException {
    String apiUrl = joinUrlPath(//from   w  ww.  j a  va 2s  .  c  om
            joinUrlPath(config.getNavigatorUrl(), "api/v" + String.valueOf(config.getApiVersion())),
            "metadata/plugin");
    HttpURLConnection conn = openConnection(new URL(apiUrl));
    conn.setRequestMethod("POST");
    String userpass = config.getUsername() + ":" + config.getPassword();
    String basicAuth = "Basic " + new String(Base64.encodeBase64(userpass.getBytes()));
    conn.addRequestProperty("Authorization", basicAuth);
    conn.addRequestProperty("Content-Type", "application/json");
    conn.setDoOutput(true);
    return conn;
}

From source file:com.cannabiscoin.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent,
        final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;/*from   w w w  .  java2  s.  c  o  m*/

    try {

        Double btcRate = 0.0;
        boolean cryptsyValue = true;
        Object result = getCoinValueBTC();

        if (result == null) {
            result = getCoinValueBTC_BTER();
            cryptsyValue = false;
            if (result == null)
                return null;
        }
        btcRate = (Double) result;

        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                    Constants.UTF_8);
            final StringBuilder content = new StringBuilder();
            Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        String rateStr = o.optString(field, null);

                        if (rateStr != null) {
                            try {
                                double rateForBTC = Double.parseDouble(rateStr);

                                rateStr = String.format("%.8f", rateForBTC * btcRate).replace(",", ".");

                                final BigInteger rate = GenericUtils.toNanoCoins(rateStr, 0);

                                if (rate.signum() > 0) {
                                    rates.put(currencyCode,
                                            new ExchangeRate(currencyCode, rate, url.getHost()));
                                    break;
                                }
                            } catch (final ArithmeticException x) {
                                log.warn("problem fetching {} exchange rate from {}: {}",
                                        new Object[] { currencyCode, url, x.getMessage() });
                            }

                        }
                    }
                }
            }

            log.info("fetched exchange rates from {}, took {} ms", url, (System.currentTimeMillis() - start));

            //Add Bitcoin information
            if (rates.size() == 0) {
                int i = 0;
                i++;
            } else {
                rates.put(CoinDefinition.cryptsyMarketCurrency,
                        new ExchangeRate(CoinDefinition.cryptsyMarketCurrency,
                                GenericUtils.toNanoCoins(String.format("%.8f", btcRate).replace(",", "."), 0),
                                cryptsyValue ? "pubapi.cryptsy.com" : "data.bter.com"));
                rates.put("m" + CoinDefinition.cryptsyMarketCurrency,
                        new ExchangeRate("m" + CoinDefinition.cryptsyMarketCurrency,
                                GenericUtils.toNanoCoins(
                                        String.format("%.5f", btcRate * 1000).replace(",", "."), 0),
                                cryptsyValue ? "pubapi.cryptsy.com" : "data.bter.com"));
            }

            return rates;
        } else {
            log.warn("http status {} when fetching {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {

        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:com.vincestyling.netroid.stack.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request) throws IOException, AuthFailureError {
    HashMap<String, String> map = new HashMap<String, String>();
    if (!TextUtils.isEmpty(mUserAgent)) {
        map.put(HTTP.USER_AGENT, mUserAgent);
    }/* w  w  w  . j  ava2s .c  om*/
    map.putAll(request.getHeaders());

    URL parsedUrl = new URL(request.getUrl());
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }

    setConnectionParametersForRequest(connection, request);

    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }

    StatusLine responseStatus = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1),
            connection.getResponseCode(), connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
        response.setEntity(entityFromConnection(connection));
    }

    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }

    return response;
}

From source file:com.scut.easyfe.network.kjFrame.http.HttpConnectStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());//from ww w  .j a  v a 2s .  c  o  m
    map.putAll(additionalHeaders);

    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);

    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode;
    try {
        responseCode = connection.getResponseCode();
    } catch (IOException e) {
        // 4.1.x/4.2.x/4.3.x ? (WWW-Authenticate: Basic realm="XXX")
        // ??401
        // java.io.IOException: No authentication challenges found
        // ?getResponseCode??
        responseCode = connection.getResponseCode();
    }
    if (responseCode == -1) {
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());

    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            String value = "";
            for (String v : header.getValue()) {
                value += (v + "; ");
            }
            Header h = new BasicHeader(header.getKey(), value);
            response.addHeader(h);
        }
    }
    return response;
}

From source file:com.ab.network.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());//www .j av  a  2  s  . c o m
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}

From source file:org.jenkinsci.plugins.publishoveronedrive.domain.JsonObjectRequest.java

private void upload(HttpURLConnection connection, String method) throws IOException {
    connection.setRequestMethod(method);
    connection.setDoOutput(true);//from   w ww  .jav a 2s .  com
    if (contentType != null) {
        connection.addRequestProperty(HEADER_CONTENT_TYPE, contentType);
    } else {
        // Leaving content type null will result in malformed requests, not setting it will result in an incorrect value
        connection.addRequestProperty(HEADER_CONTENT_TYPE, OCTET_STREAM);
    }
    DataOutputStream outputStream = null;
    try {
        OutputStream stream = connection.getOutputStream();
        outputStream = new DataOutputStream(stream);
        IOUtils.copy(bodyStream, outputStream);
        outputStream.flush();
    } finally {
        closeQuietly(bodyStream);
        closeQuietly(outputStream);
    }
}

From source file:com.handsome.frame.android.volley.stack.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request) throws IOException, AuthFailureError {
    HashMap<String, String> map = new HashMap<String, String>();
    if (!TextUtils.isEmpty(mUserAgent)) {
        map.put(HTTP.USER_AGENT, mUserAgent);
    }//from  w w  w  .jav  a 2  s.c  o m
    map.putAll(request.getHeaders());

    URL parsedUrl = new URL(request.getUrl());
    HttpURLConnection connection = openConnection(parsedUrl, request);

    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    if (HandsomeApplication.getCookies() != null) {
        HDLog.d(TAG + "-Req-Cookie:", HandsomeApplication.getCookies().toString());
        connection.addRequestProperty("Cookie", HandsomeApplication.getCookies());
    } else {
        HDLog.d(TAG + "-Req-Cookie:", "null");
    }
    setConnectionParametersForRequest(connection, request);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }

    StatusLine responseStatus = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1),
            connection.getResponseCode(), connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            if (header.getKey().equalsIgnoreCase("Set-Cookie")) {
                List<String> cookies = header.getValue();
                HashMap<String, HttpCookie> cookieMap = new HashMap<String, HttpCookie>();
                for (String string : cookies) {
                    List<HttpCookie> cookie = HttpCookie.parse(string);
                    for (HttpCookie httpCookie : cookie) {
                        cookieMap.put(httpCookie.getName(), httpCookie);
                    }
                }
                HandsomeApplication.setCookies(cookieMap);
                HDLog.d(TAG + "-Rsp-Cookie:", HandsomeApplication.getCookies().toString());
            } else {
                Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
                response.addHeader(h);
            }
        }
    }

    return response;
}