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.android.volley.toolbox.http.HurlStack.java

@SuppressWarnings("deprecation")
/* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST:
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getBody();
        if (postBody != null) {
            // Prepare output. There is no need to set Content-Length explicitly,
            // since this is handled by HttpURLConnection using the size of the prepared
            // output stream.
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(postBody);/* w w w .  ja  v a2s  . c o m*/
            out.close();
        }
        break;
    case Method.GET:
        // Not necessary to set the request method because connection defaults to GET but
        // being explicit here.
        connection.setRequestMethod("GET");
        break;
    case Method.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case Method.POST:
        connection.setRequestMethod("POST");
        addBodyIfExists(connection, request);
        break;
    case Method.PUT:
        connection.setRequestMethod("PUT");
        addBodyIfExists(connection, request);
        break;
    case Method.HEAD:
        connection.setRequestMethod("HEAD");
        break;
    case Method.OPTIONS:
        connection.setRequestMethod("OPTIONS");
        break;
    case Method.TRACE:
        connection.setRequestMethod("TRACE");
        break;
    case Method.PATCH:
        //connection.setRequestMethod("PATCH");
        //If server doesnt support patch uncomment this
        connection.setRequestMethod("POST");
        connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
        addBodyIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:cn.edu.hfut.dmic.webcollector.example.DemoJsonCrawler.java

public DemoJsonCrawler(String crawlPath) {
    super(crawlPath);
    HttpRequesterImpl myRequester = new HttpRequesterImpl() {
        /*Override??http(HttpURLConnection)*/
        @Override//from  ww w.jav a 2 s .co m
        public void configConnection(HttpURLConnection con) {

            try {
                con.setRequestMethod("POST");
            } catch (ProtocolException ex) {
                ex.printStackTrace();
            }

            /*http*/
            con.addRequestProperty("xxx", "xxxxxxx");
        }

    };
    myRequester.setCookie("cookie");
    this.setHttpRequester(myRequester);

}

From source file:org.jclouds.demo.tweetstore.integration.TweetStoreLiveTest.java

@Test(dependsOnMethods = "shouldFail")
public void testPrimeContainers() throws IOException, InterruptedException {
    URL gurl = new URL(url, "/store/do");

    for (String context : new String[] { "S3", "Azure", "CloudFiles" }) {
        System.out.println("storing at context: " + context);
        HttpURLConnection connection = (HttpURLConnection) gurl.openConnection();
        connection.addRequestProperty("X-AppEngine-QueueName", "twitter");
        connection.addRequestProperty("context", context);
        InputStream i = connection.getInputStream();
        String string = IOUtils.toString(i);
        assert string.indexOf("Done!") >= 0 : string;
        connection.disconnect();//w w  w  . ja  va  2s.c  om
    }

    System.err.println("sleeping 10 seconds to allow for eventual consistency delay");
    Thread.sleep(10000);
    for (BlobStoreContext<?, ?> context : contexts) {

        assert context.createInputStreamMap(container).size() > 0 : context.getEndPoint();
    }
}

From source file:dk.itst.oiosaml.sp.service.util.HttpSOAPClient.java

private void addContentTypeHeader(String xml, HttpURLConnection c) {
    String soapVersion = Utils.getSoapVersion(xml);
    if (SOAPConstants.SOAP11_NS.equals(soapVersion)) {
        c.addRequestProperty("Content-Type", "text/xml; charset=utf-8");
    } else if (SOAPConstants.SOAP12_NS.equals(soapVersion)) {
        c.addRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
    } else {/* w ww .  ja  v a 2s  .c  o  m*/
        throw new UnsupportedOperationException("SOAP version " + soapVersion + " not supported");
    }
}

From source file:io.helixservice.feature.configuration.cloudconfig.CloudConfigResourceLocator.java

private Optional<InputStream> requestCloudConfigProperties(String resourcePath, Optional<InputStream> result) {
    String cloudConfigResource = resourcePath.substring(0, resourcePath.lastIndexOf(APPLICATION_YAML_FILE))
            .replace("default", "default");
    String url = serviceUri + "/" + cloudConfigResource;

    try {/*from w w w  .j  a va  2  s  . c om*/
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("GET");
        connection.addRequestProperty(AUTHORIZATION_HEADER, httpBasicHeader);

        if (connection.getResponseCode() == 200) {
            InputStream inputStream = connection.getInputStream();
            InputStream extractedPropertiesInputStream = extractProperties(inputStream);
            result = Optional.of(extractedPropertiesInputStream);
            inputStream.close();
        } else {
            LOG.error("Unable to get Cloud Config due to httpStatusCode=" + connection.getResponseCode()
                    + " for cloudConfigUrl=" + url);
        }
    } catch (IOException e) {
        LOG.error("Unable to connect to Cloud Config server at cloudConfigUrl=" + url + " exception="
                + e.getClass().getSimpleName() + " exceptionMessage=" + e.getMessage());
    }
    return result;
}

From source file:org.apache.hadoop.mapred.TestShuffleHandler.java

private static int getShuffleResponseCode(ShuffleHandler shuffle, Token<JobTokenIdentifier> jt)
        throws IOException {
    URL url = new URL("http://127.0.0.1:" + shuffle.getConfig().get(ShuffleHandler.SHUFFLE_PORT_CONFIG_KEY)
            + "/mapOutput?job=job_12345_0001&reduce=0&map=attempt_12345_1_m_1_0");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    String encHash = SecureShuffleUtils.hashFromString(SecureShuffleUtils.buildMsgFrom(url),
            JobTokenSecretManager.createSecretKey(jt.getPassword()));
    conn.addRequestProperty(SecureShuffleUtils.HTTP_HEADER_URL_HASH, encHash);
    conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_NAME, ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
    conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_VERSION, ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
    conn.connect();/*from w w  w.  j  av  a 2  s.  c om*/
    int rc = conn.getResponseCode();
    conn.disconnect();
    return rc;
}

From source file:de.rallye.test.GroupsTest.java

@Test
public void testLogin() throws IOException {

    Authenticator.setDefault(new Authenticator() {
        @Override/*from  ww  w . j a va 2s.  co m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            String realm = getRequestingPrompt();
            assertEquals("Should be right Realm", "RallyeNewUser", realm);
            return new PasswordAuthentication(String.valueOf(1), "test".toCharArray());
        }
    });
    URL url = new URL("http://127.0.0.1:10111/groups/1");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("PUT");

    conn.setDoOutput(true);
    conn.addRequestProperty("Content-Type", "application/json");
    //      conn.setFixedLengthStreamingMode(post.length);
    conn.getOutputStream().write(MockDataAdapter.validLogin.getBytes());

    int code = conn.getResponseCode();

    Authenticator.setDefault(null);

    try {
        assertEquals("Code should be 200", 200, code);
    } catch (AssertionError e) {
        System.err.println("This is the content:");
        List<String> contents = IOUtils.readLines((InputStream) conn.getContent());
        for (String line : contents)
            System.err.println(line);
        throw e;
    }

}

From source file:com.forgerock.wisdom.oauth2.info.internal.StandardIntrospectionService.java

@Override
public TokenInfo introspect(final String token) {

    try {/* w  w  w .j a v a  2s.c om*/
        HttpURLConnection connection = (HttpURLConnection) new URL(baseUrl).openConnection();
        connection.getOutputStream().write(format("token=%s", token).getBytes());
        connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setDoOutput(true);
        if (bearerToken != null) {
            connection.addRequestProperty("Authorization", format("Bearer %s", bearerToken));
        }
        int code = connection.getResponseCode();
        if (code != 200) {
            return TokenInfo.INVALID;
        }

        try (InputStream stream = connection.getInputStream()) {
            JsonNode node = mapper.readTree(stream);
            if (node.get("active").asBoolean()) {

                JsonNode exp = node.get("exp");
                long expiresIn = 0;
                if (exp != null) {
                    expiresIn = exp.asLong() - System.currentTimeMillis();
                }

                JsonNode scope = node.get("scope");
                String[] scopes = null;
                if (scope != null) {
                    scopes = scope.asText().split(" ");
                }

                return new TokenInfo(true, expiresIn, scopes);
            }
        }

    } catch (IOException e) {
        // Ignored
    }

    return TokenInfo.INVALID;
}

From source file:com.orchestra.portale.external.services.manager.CiRoService.java

@Override
public String getResponse(Map<String, String[]> mapParams) {
    try {/* ww w. ja  va 2 s  .c  o m*/
        HttpURLConnection urlConnection = (HttpURLConnection) new URL(getUrl).openConnection();
        urlConnection.setConnectTimeout(15000);
        urlConnection.setReadTimeout(30000);
        urlConnection.addRequestProperty("Accept-Language", Locale.getDefault().toString().replace('_', '-'));
        String result = IOUtils.toString(urlConnection.getInputStream());
        urlConnection.disconnect();
        return result;
    } catch (IOException e) {
        return "response{code:1,error:" + e.getMessage() + "}";
    }
}

From source file:org.openmrs.module.odkconnector.serialization.web.CohortWebConnectorTest.java

@Test
public void serialize_shouldDisplayAllCohortInformation() throws Exception {

    // compose url
    URL u = new URL(SERVER_URL + "/module/odkconnector/download/cohort.form");

    // setup http url connection
    HttpURLConnection connection = (HttpURLConnection) u.openConnection();
    connection.setDoOutput(true);//from www  .j  a  v a2  s  . c o  m
    connection.setRequestMethod("POST");
    connection.setConnectTimeout(8000);
    connection.setReadTimeout(8000);
    connection.addRequestProperty("Content-type", "application/octet-stream");

    // write auth details to connection
    DataOutputStream outputStream = new DataOutputStream(new GZIPOutputStream(connection.getOutputStream()));
    outputStream.writeUTF("admin");
    outputStream.writeUTF("test");
    outputStream.writeBoolean(false);
    outputStream.close();

    DataInputStream inputStream = new DataInputStream(new GZIPInputStream(connection.getInputStream()));
    Integer responseStatus = inputStream.readInt();

    if (responseStatus == HttpURLConnection.HTTP_OK) {

        Integer cohortCounts = inputStream.readInt();
        System.out.println("Number of cohorts: " + cohortCounts);

        for (int i = 0; i < cohortCounts; i++) {
            System.out.println("Cohort ID: " + inputStream.readInt());
            System.out.println("Cohort Name: " + inputStream.readUTF());
        }
    }
    inputStream.close();
}