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:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java

public static HttpResponse doDelete(URL endpoint, Map<String, String> headers) throws Exception {
    HttpURLConnection urlConnection = null;
    try {/*from   w  w w  .j a v  a  2 s. c  om*/
        urlConnection = (HttpURLConnection) endpoint.openConnection();
        try {
            urlConnection.setRequestMethod("DELETE");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support Delete??", e);
        }
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setAllowUserInteraction(false);

        // setting headers
        if (headers != null && headers.size() > 0) {
            Iterator<String> itr = headers.keySet().iterator();
            while (itr.hasNext()) {
                String key = itr.next();
                urlConnection.setRequestProperty(key, headers.get(key));
            }
        }

        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
        }
        Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator();
        Map<String, String> responseHeaders = new HashMap();
        while (itr.hasNext()) {
            String key = itr.next();
            if (key != null) {
                responseHeaders.put(key, urlConnection.getHeaderField(key));
            }
        }
        return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), responseHeaders);

    } catch (IOException e) {
        throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:net.ae97.pokebot.extensions.scrolls.ExperimentalPriceCommand.java

@Override
public void runEvent(CommandEvent event) {
    if (event.getArgs().length == 0 || (event.getArgs()[0].equals("-d") && event.getArgs().length < 3)) {
        event.respond("Usage: .price <-d days> [name]");
        return;//from w  ww.  j a  va 2s  .c o m
    }
    int days = 2;
    String[] name = event.getArgs();
    if (event.getArgs()[0].equals("-d")) {
        name = new String[event.getArgs().length - 2];
        for (int i = 2; i < event.getArgs().length; i++) {
            name[i - 2] = event.getArgs()[i];
        }
        try {
            days = Integer.parseInt(event.getArgs()[1]);
        } catch (NumberFormatException e) {
            event.respond("Usage: .price <-d days> [name]");
            return;
        }
        if (days > 10 || days < 0) {
            event.respond("The days must be between 1 and 10 (inclusive)");
            return;
        }
    }
    try {
        URL playerURL = new URL(
                url.replace("{days}", Integer.toString(days)).replace("{name}", StringUtils.join(name, "%20")));
        List<String> lines = new LinkedList<>();
        HttpURLConnection conn = (HttpURLConnection) playerURL.openConnection();
        conn.setRequestProperty("User-Agent", "PokeBot - " + PokeBot.VERSION);
        conn.connect();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        }

        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(StringUtils.join(lines, "\n"));
        JsonObject obj = element.getAsJsonObject();

        String result = obj.get("msg").getAsString();
        if (!result.equalsIgnoreCase("success")) {
            event.respond("Scroll not found");
            return;
        }
        JsonObject dataObject = obj.get("data").getAsJsonArray().get(0).getAsJsonObject();

        StringBuilder builder = new StringBuilder();

        builder.append("Buy: ").append(dataObject.get("buy").getAsJsonObject().get("price").getAsInt())
                .append(" Gold - ");
        builder.append("Bought: ").append(dataObject.get("buy").getAsJsonObject().get("pop").getAsInt())
                .append(" - ");
        builder.append("Sell: ").append(dataObject.get("sell").getAsJsonObject().get("price").getAsInt())
                .append(" Gold - ");
        builder.append("Sold: ").append(dataObject.get("sell").getAsJsonObject().get("pop").getAsInt());
        String[] message = builder.toString().split("\n");
        for (String msg : message) {
            event.respond("" + msg);
        }

    } catch (IOException | JsonSyntaxException | IllegalStateException ex) {
        PokeBot.getLogger().log(Level.SEVERE,
                "Error on getting scroll for Scrolls for '" + StringUtils.join(event.getArgs(), " ") + "'", ex);
        event.respond("Error on getting scroll: " + ex.getLocalizedMessage());

    }
}

From source file:junit.org.rapidpm.microservice.demo.ServletTest.java

@Test
public void testServletGetReq001() throws Exception {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", USER_AGENT);

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);

    final StringBuffer response;
    try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
        String inputLine;//from ww  w . jav a2  s .  c  o  m
        response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
    }
    //    System.out.println("response = " + response);
    Assert.assertEquals("Hello World CDI Service", response.toString());
}

From source file:oauth.signpost.basic.DefaultOAuthProvider.java

protected HttpRequest createRequest(String endpointUrl) throws MalformedURLException, IOException {
    HttpURLConnection connection = (HttpURLConnection) new URL(endpointUrl).openConnection();
    connection.setRequestMethod("POST");
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty("Content-Length", "0");
    return new HttpURLConnectionRequestAdapter(connection);
}

From source file:io.takari.jdkget.transport.OracleWebsiteTransport.java

public boolean downloadJdk(Arch arch, JdkVersion jdkVersion, File jdkImage, IOutput output) throws IOException {

    String url = String.format(JDK_URL_FORMAT, jdkVersion.major, jdkVersion.revision, jdkVersion.buildNumber,
            jdkVersion.major, jdkVersion.revision, arch.getArch(), arch.getExtension());
    output.info("Downloading " + url);

    // Oracle does some redirects so we have to follow a couple before we win the JDK prize
    URL jdkUrl;//  w ww . j a  v  a 2 s. c o  m
    int response = 0;
    HttpURLConnection connection;
    for (int retry = 0; retry < 4; retry++) {
        jdkUrl = new URL(url);
        connection = (HttpURLConnection) jdkUrl.openConnection();
        connection.setRequestProperty("Cookie", OTN_COOKIE);
        response = connection.getResponseCode();
        if (response == 200) {
            try (InputStream is = connection.getInputStream();
                    OutputStream os = new FileOutputStream(jdkImage)) {
                IOUtils.copy(is, os);
            }
            return true;
        } else if (response == 302) {
            url = connection.getHeaderField("Location");
        }
    }
    return false;
}

From source file:com.ibm.iot.auto.bluemix.samples.ui.Connection.java

private HttpURLConnection createHttpURLGetConnection(String urlTail) throws IOException {
    URL url = new URL(apiBaseUrl + urlTail + "?tenant_id=" + tenantId);
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setRequestProperty("Authorization", "Basic " + authorizationValue);
    httpURLConnection.setRequestMethod("GET");
    return httpURLConnection;
}

From source file:com.ibm.iot.auto.bluemix.samples.ui.Connection.java

private HttpURLConnection createHttpURLGetConnection(String urlTail, String parameters) throws IOException {
    URL url = new URL(apiBaseUrl + urlTail + "?tenant_id=" + tenantId + "&" + parameters);
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setRequestProperty("Authorization", "Basic " + authorizationValue);
    httpURLConnection.setRequestMethod("GET");
    return httpURLConnection;
}

From source file:com.adyen.httpclient.HttpURLConnectionClient.java

/**
 * Sets content type/*from  ww  w.jav a 2  s.  c  o m*/
 */
private HttpURLConnection setContentType(HttpURLConnection httpConnection, String contentType) {
    httpConnection.setRequestProperty("Content-Type", contentType);
    return httpConnection;
}

From source file:com.jamfsoftware.jss.healthcheck.controller.HTTPController.java

public int returnGETResponseCode(String URL) throws Exception {
    URL obj = new URL(URL);

    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    TrustModifier.relaxHostChecking(con);

    con.setRequestMethod("GET");
    con.setRequestProperty("User_Agent", USER_AGENT);
    Base64 b = new Base64();
    String encoding = b.encodeAsString((username + ":" + password).getBytes());
    con.setRequestProperty("Authorization", "Basic " + encoding);

    return con.getResponseCode();
}