Example usage for javax.net.ssl HttpsURLConnection setRequestProperty

List of usage examples for javax.net.ssl HttpsURLConnection setRequestProperty

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setRequestProperty.

Prototype

public void setRequestProperty(String key, String value) 

Source Link

Document

Sets the general request property.

Usage

From source file:me.rojo8399.placeholderapi.impl.Metrics.java

/**
 * Sends the data to the bStats server./*from  w  ww  .j a  v  a2 s  .c o  m*/
 *
 * @param data
 *            The data to send.
 * @throws Exception
 *             If the request failed.
 */
private static void sendData(JsonObject data) throws Exception {
    Validate.notNull(data, "Data cannot be null");
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip
    // our
    // request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We
    // send
    // our
    // data
    // in
    // JSON
    // format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response
    // - Just send our data :)
}

From source file:org.sufficientlysecure.keychain.ui.linked.LinkedIdCreateGithubFragment.java

private void revokeToken(final String token) {

    new AsyncTask<Void, Void, Void>() {
        @Override//from   w ww .  ja  va  2s . c o m
        protected Void doInBackground(Void... dummy) {
            try {
                HttpsURLConnection nection = (HttpsURLConnection) new URL("https://api.github.com/applications/"
                        + BuildConfig.GITHUB_CLIENT_ID + "/tokens/" + token).openConnection();
                nection.setRequestMethod("DELETE");
                String encoded = Base64.encodeToString(
                        (BuildConfig.GITHUB_CLIENT_ID + ":" + BuildConfig.GITHUB_CLIENT_SECRET).getBytes(),
                        Base64.DEFAULT);
                nection.setRequestProperty("Authorization", "Basic " + encoded);
                nection.connect();
            } catch (IOException e) {
                // nvm
            }
            return null;
        }
    }.execute();

}

From source file:gov.nih.nci.cabig.ccts.security.SecureURL.java

/**
 * Retrieve the contents from the given URL as a String, assuming the URL's
 * server matches what we expect it to match.
 *//*from   w w  w  .  j a  va  2  s .  c o m*/
public static String retrieve(String url) throws IOException {
    if (log.isTraceEnabled()) {
        log.trace("entering retrieve(" + url + ")");
    }
    BufferedReader r = null;
    try {
        URL u = new URL(url);
        if (!u.getProtocol().equals("https")) {
            // IOException may not be the best exception we could throw here
            // since the problem is with the URL argument we were passed,
            // not
            // IO. -awp9
            log.error("retrieve(" + url + ") on an illegal URL since protocol was not https.");
            throw new IOException("only 'https' URLs are valid for this method");
        }

        // JAP: changing to allow validation of Globus-style host names.
        // URLConnection uc = u.openConnection();
        HttpsURLConnection uc = (HttpsURLConnection) u.openConnection();
        uc.setHostnameVerifier(new HostnameVerifier() {

            public boolean verify(String hostname, SSLSession session) {
                boolean valid = false;
                try {
                    String expectedHostname = hostname.toLowerCase();
                    log.debug("expectedHostname = " + expectedHostname);

                    String subjectDN = session.getPeerCertificateChain()[0].getSubjectDN().getName()
                            .toLowerCase();
                    log.debug("subjectDN = " + subjectDN);
                    String assertedHostname = null;
                    for (String part : subjectDN.split(",")) {
                        String[] nameValue = part.split("=");
                        String name = nameValue[0].toLowerCase().trim();
                        String value = nameValue[1].trim();
                        if (name.equals("cn")) {
                            assertedHostname = value;
                            break;
                        }
                    }
                    if (assertedHostname == null) {
                        log.warn("No common name found in subject distinguished name.");
                        return false;
                    }
                    log.debug("assertedHostname = " + assertedHostname);
                    if (assertedHostname.startsWith("host/")) {
                        expectedHostname = "host/" + expectedHostname;
                        log.debug("detected Globus-style common name, expectedHostname = " + expectedHostname);
                    }
                    valid = assertedHostname.equals(expectedHostname);
                    log.debug("valid = " + valid);
                } catch (Exception ex) {
                    log.warn(ex);
                }
                return valid;
            }

        });

        uc.setRequestProperty("Connection", "close");
        r = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        String line;
        StringBuffer buf = new StringBuffer();
        while ((line = r.readLine()) != null)
            buf.append(line + "\n");
        return buf.toString();
    } finally {
        try {
            if (r != null)
                r.close();
        } catch (IOException ex) {
            // ignore
        }
    }
}

From source file:com.example.android.networkconnect.MainActivity.java

private String https_token(String urlString) throws IOException {

    String token = null;//from  w  w  w. ja va  2 s.  com
    URL url = new URL(urlString);

    if (url.getProtocol().toLowerCase().equals("https")) {
        trustAllHosts();
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setChunkedStreamingMode(0);

        conn.setRequestProperty("User-Agent", "e-venement-app/");

        List<String> cookies1 = conn.getHeaderFields().get("Set-Cookie");

        for (int g = 0; g < cookies1.size(); g++) {
            Log.i(TAG, "Cookie_list: " + cookies1.get(g).toString());
            Cookie cookie;
            String[] cook = cookies1.get(g).toString().split(";");

            String[] subcook = cook[0].split("=");
            token = subcook[1];
            Log.i(TAG, "Sub Cook: " + subcook[1]);

            // subcook[1];
        }
    }
    //conn.disconnect();
    return token;
}

From source file:br.com.intelidev.dao.DadosDao.java

public List<Dados> get_stream_data(String stream_api, String user, String pass) {

    HttpsURLConnection conn = null;
    List<Dados> list_return = new ArrayList<>();
    int i;//from   w  ww  .  j a va2 s  . co m

    try {
        // Create url to the Device Cloud server for a given web service request
        //00000000-00000000-00409DFF-FF6064F8/xbee.analog/[00:13:A2:00:40:E6:5A:88]!/AD1
        ObjectMapper mapper = new ObjectMapper();
        URL url = new URL("https://devicecloud.digi.com/ws/v1/streams/history/" + stream_api);
        //URL url = new URL("https://devicecloud.digi.com/ws/v1/streams/history/00000000-00000000-00409DFF-FF6064F8/xbee.analog/[00:13:A2:00:40:E6:5A:88]!/AD1");
        conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("GET");

        // Build authentication string
        String userpassword = user + ":" + pass;
        System.out.println(userpassword);

        // can change this to use a different base64 encoder
        String encodedAuthorization = Base64.encodeBase64String(userpassword.getBytes()).trim();

        // set request headers
        conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
        // Get input stream from response and convert to String
        InputStream is = conn.getInputStream();

        Scanner isScanner = new Scanner(is);
        StringBuffer buf = new StringBuffer();
        while (isScanner.hasNextLine()) {
            buf.append(isScanner.nextLine() + "\n");
        }
        String responseContent = buf.toString();

        // add line returns between tags to make it a bit more readable
        responseContent = responseContent.replaceAll("><", ">\n<");

        // Output response to standard out
        System.out.println(responseContent);
        // Convert JSON string to Object
        StreamDados stream = mapper.readValue(responseContent, StreamDados.class);
        //System.out.println(stream.getList());
        System.out.println(stream.getList().size());
        for (i = 0; i < stream.getList().size(); i++) {
            list_return.add(stream.getList().get(i));
            //System.out.println("ts: "+ stream.getList().get(i).getTimestamp() + "Value: " + stream.getList().get(i).getValue());

        }

    } catch (Exception e) {
        // Print any exceptions that occur
        System.out.println("br.com.intelidev.dao.DadosDao.get_stream_data() e" + e);
    } finally {
        if (conn != null)
            conn.disconnect();
    }

    return list_return;
}

From source file:com.pearson.pdn.learningstudio.core.AbstractService.java

/**
 * Performs HTTP operations using the selected authentication method
 * //from w  ww. ja v  a 2s .  c o  m
 * @param extraHeaders   Extra headers to include in the request
 * @param method   The HTTP Method to user
 * @param relativeUrl   The URL after .com (/me)
 * @param body   The body of the message
 * @return Output in the preferred data format
 * @throws IOException
 */
protected Response doMethod(Map<String, String> extraHeaders, HttpMethod method, String relativeUrl,
        String body) throws IOException {

    if (body == null) {
        body = "";
    }

    // append .xml extension when XML data format enabled.
    if (dataFormat == DataFormat.XML) {
        logger.debug("Using XML extension on route");

        String queryString = "";
        int queryStringIndex = relativeUrl.indexOf('?');
        if (queryStringIndex != -1) {
            queryString = relativeUrl.substring(queryStringIndex);
            relativeUrl = relativeUrl.substring(0, queryStringIndex);
        }

        String compareUrl = relativeUrl.toLowerCase();

        if (!compareUrl.endsWith(".xml")) {
            relativeUrl += ".xml";
        }

        if (queryStringIndex != -1) {
            relativeUrl += queryString;
        }
    }

    final String fullUrl = API_DOMAIN + relativeUrl;

    if (logger.isDebugEnabled()) {
        logger.debug("REQUEST - Method: " + method.name() + ", URL: " + fullUrl + ", Body: " + body);
    }

    URL url = new URL(fullUrl);
    Map<String, String> oauthHeaders = getOAuthHeaders(method, url, body);

    if (oauthHeaders == null) {
        throw new RuntimeException("Authentication method not selected. SEE useOAuth# methods");
    }

    if (extraHeaders != null) {
        for (String key : extraHeaders.keySet()) {
            if (!oauthHeaders.containsKey(key)) {
                oauthHeaders.put(key, extraHeaders.get(key));
            } else {
                throw new RuntimeException("Extra headers can not include OAuth headers");
            }
        }
    }

    HttpsURLConnection request = (HttpsURLConnection) url.openConnection();
    try {
        request.setRequestMethod(method.toString());

        Set<String> oauthHeaderKeys = oauthHeaders.keySet();
        for (String oauthHeaderKey : oauthHeaderKeys) {
            request.addRequestProperty(oauthHeaderKey, oauthHeaders.get(oauthHeaderKey));
        }

        request.addRequestProperty("User-Agent", getServiceIdentifier());

        if ((method == HttpMethod.POST || method == HttpMethod.PUT) && body.length() > 0) {
            if (dataFormat == DataFormat.XML) {
                request.setRequestProperty("Content-Type", "application/xml");
            } else {
                request.setRequestProperty("Content-Type", "application/json");
            }

            request.setRequestProperty("Content-Length", String.valueOf(body.getBytes("UTF-8").length));
            request.setDoOutput(true);

            DataOutputStream out = new DataOutputStream(request.getOutputStream());
            try {
                out.writeBytes(body);
                out.flush();
            } finally {
                out.close();
            }
        }

        Response response = new Response();
        response.setMethod(method.toString());
        response.setUrl(url.toString());
        response.setStatusCode(request.getResponseCode());
        response.setStatusMessage(request.getResponseMessage());
        response.setHeaders(request.getHeaderFields());

        InputStream inputStream = null;
        if (response.getStatusCode() < ResponseStatus.BAD_REQUEST.code()) {
            inputStream = request.getInputStream();
        } else {
            inputStream = request.getErrorStream();
        }

        boolean isBinary = false;
        if (inputStream != null) {
            StringBuilder responseBody = new StringBuilder();

            String contentType = request.getContentType();
            if (contentType != null) {
                if (!contentType.startsWith("text/") && !contentType.startsWith("application/xml")
                        && !contentType.startsWith("application/json")) { // assume binary
                    isBinary = true;
                    inputStream = new Base64InputStream(inputStream, true); // base64 encode
                }
            }

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            try {
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    responseBody.append(line);
                }
            } finally {
                bufferedReader.close();
            }

            response.setContentType(contentType);

            if (isBinary) {
                String content = responseBody.toString();
                if (content.length() == 0) {
                    response.setBinaryContent(new byte[0]);
                } else {
                    response.setBinaryContent(Base64.decodeBase64(responseBody.toString()));
                }
            } else {
                response.setContent(responseBody.toString());
            }
        }

        if (logger.isDebugEnabled()) {
            if (isBinary) {
                logger.debug("RESPONSE - binary response omitted");
            } else {
                logger.debug("RESPONSE - " + response.toString());
            }
        }

        return response;
    } finally {
        request.disconnect();
    }

}

From source file:hudson.plugins.sitemonitor.SiteMonitorRecorder.java

private HttpURLConnection getConnection(String urlString)
        throws MalformedURLException, IOException, NoSuchAlgorithmException, KeyManagementException {

    if (urlString.startsWith("https://")) {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        SSLContext.setDefault(ctx);

        HttpsURLConnection connection = (HttpsURLConnection) ProxyConfiguration.open(new URL(urlString));
        connection.setHostnameVerifier(new HostnameVerifier() {

            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }//  w w  w. j ava  2 s .  c om
        });
        return connection;

    } else if (urlString.contains("@")) {

        URL passedURL = new URL(urlString);
        String creds = urlString.substring(urlString.indexOf("//") + 2, urlString.indexOf("@"));
        String userName = creds.substring(0, creds.indexOf(":"));
        String passWord = creds.substring(creds.indexOf(":") + 1, creds.length());
        String userPassword = userName + ":" + passWord;
        // TODO cambiar implementacin de Base64
        String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
        // TODO soporta proxy?
        HttpURLConnection connection = (HttpURLConnection) passedURL.openConnection();
        connection.setRequestProperty("Authorization", "Basic " + encoding);
        return connection;

    } else {
        return (HttpURLConnection) ProxyConfiguration.open(new URL(urlString));
    }
}

From source file:com.example.android.networkconnect.MainActivity.java

private String https_test(String urlString) throws IOException {

    String token = "";
    URL url = new URL(urlString);

    Log.i(TAG, "Protocol: " + url.getProtocol().toString());

    // if (url.getProtocol().toLowerCase().equals("https")) {
    trustAllHosts();/*from  w ww. j  ava2  s.com*/

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    conn.setReadTimeout(20000 /* milliseconds */);
    conn.setConnectTimeout(25000 /* milliseconds */);
    // conn.setRequestMethod("GET");
    conn.setDoInput(true);
    conn.setDoOutput(true);

    conn.setChunkedStreamingMode(0);

    conn.setRequestProperty("User-Agent", "e-venement-app/");

    // OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    //writer.getEncoding();
    //writer.write("&signin[username]=antoine");
    //writer.write("&signin[password]=android2015@");
    //writer.write("?control[id]=");
    //writer.write("&control[ticket_id]=2222");
    //writer.write("&control[checkpoint_id]=1");
    //  writer.write("&control[comment]=");

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //On cre la liste qui contiendra tous nos paramtres

    //Et on y rajoute nos paramtres
    nameValuePairs.add(new BasicNameValuePair("signin[username]", "antoine"));
    nameValuePairs.add(new BasicNameValuePair("signin[password]", "android2015@"));
    //nameValuePairs.add(new BasicNameValuePair("control[id]", ""));
    //nameValuePairs.add(new BasicNameValuePair("control[ticket_id]", "2222"));
    //nameValuePairs.add(new BasicNameValuePair("control[checkpoint_id]", "1"));
    //nameValuePairs.add(new BasicNameValuePair("control[comment]", ""));

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer2 = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer2.write(getQuery(nameValuePairs));
    writer2.flush();
    //writer2.close();
    //os.close();

    // conn.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    //writer.write("&signin[_csrf_token]="+CSRFTOKEN);
    //writer.flush();

    conn.connect();

    String headerName = null;

    for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
        //data=data+"Header Nme : " + headerName;
        //data=data+conn.getHeaderField(i);
        // Log.i (TAG,headerName);
        Log.i(TAG, headerName + ": " + conn.getHeaderField(i));

    }

    int responseCode = conn.getResponseCode();

    if (responseCode == conn.HTTP_OK) {
        final String COOKIES_HEADER = "Set-Cookie";
        cookie = conn.getHeaderField(COOKIES_HEADER);
    }

    if (conn.getInputStream() != null) {

        // token =getStringFromInputStream(conn.getInputStream());
        Log.i(TAG, readIt(conn.getInputStream(), 15000));
        token = readIt(conn.getInputStream(), 15000);
        Log.i(TAG, getStringFromInputStream(conn.getInputStream()));
        //data=readIt(conn.getInputStream(),7500);
        //Log.i(TAG,token);
        //token=readIt(conn.getInputStream(),7500);
    }
    //conn.connect();
    // List<String> cookiesList = conn.getHeaderFields().get("Set-Cookie");

    // }
    //conn.disconnect();
    return token;
}

From source file:org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest.java

public RestResponse httpsSendGet(String url, Map<String, String> headers) throws IOException {

    RestResponse restResponse = new RestResponse();
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    // optional default is GET
    con.setRequestMethod("GET");
    // add request header
    if (headers != null) {
        for (Entry<String, String> header : headers.entrySet()) {
            String key = header.getKey();
            String value = header.getValue();
            con.setRequestProperty(key, value);
        }// w w w .j  a v a2s  .c  om

    }

    int responseCode = con.getResponseCode();
    logger.debug("Send GET http request, url: {}", url);
    logger.debug("Response Code: {}", responseCode);

    StringBuffer response = new StringBuffer();
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
    } catch (Exception e) {
        logger.debug("response body is null");
    }

    String result;

    try {

        result = IOUtils.toString(con.getErrorStream());
        response.append(result);

    } catch (Exception e2) {
        // result = null;
    }
    logger.debug("Response body: {}", response);

    // print result

    restResponse.setErrorCode(responseCode);

    if (response != null) {
        restResponse.setResponse(response.toString());
    }

    restResponse.setErrorCode(responseCode);
    // restResponse.setResponse(result);
    Map<String, List<String>> headerFields = con.getHeaderFields();
    restResponse.setHeaderFields(headerFields);
    String responseMessage = con.getResponseMessage();
    restResponse.setResponseMessage(responseMessage);

    con.disconnect();

    return restResponse;
}

From source file:org.wso2.am.integration.tests.other.APIImportExportTestCase.java

/**
 * Upload a file to the given URL//w  w  w . j  a  v a2s  . co  m
 *
 * @param importUrl URL to be file upload
 * @param fileName  Name of the file to be upload
 * @throws IOException throws if connection issues occurred
 */
private void importAPI(String importUrl, File fileName, String user, char[] pass) throws IOException {
    //open import API url connection and deploy the exported API
    URL url = new URL(importUrl);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");

    FileBody fileBody = new FileBody(fileName);
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
    multipartEntity.addPart("file", fileBody);

    connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());
    connection.setRequestProperty(APIMIntegrationConstants.AUTHORIZATION_HEADER,
            "Basic " + encodeCredentials(user, pass));
    OutputStream out = connection.getOutputStream();
    try {
        multipartEntity.writeTo(out);
    } finally {
        out.close();
    }
    int status = connection.getResponseCode();
    BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String temp;
    StringBuilder response = new StringBuilder();
    while ((temp = read.readLine()) != null) {
        response.append(temp);
    }
    Assert.assertEquals(status, HttpStatus.SC_CREATED, "Response code is not as expected : " + response);
}