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:net.portalblockz.portalbot.urlshorteners.GooGl.java

@Override
public String shorten(String url) {
    StringBuilder response = new StringBuilder();
    try {/* www. j av  a2  s. co m*/
        URL req = new URL("https://www.googleapis.com/urlshortener/v1/url");

        HttpsURLConnection con = (HttpsURLConnection) req.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setDoOutput(true);

        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes("{\"longUrl\": \"" + url + "\"}");
        wr.flush();
        wr.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        JSONObject res = new JSONObject(response.toString());
        if (res.optString("id") != null)
            return res.getString("id");

    } catch (Exception ignored) {
        ignored.printStackTrace();
        System.out.print(response.toString());
    }
    return null;
}

From source file:com.clueride.auth.Auth0ConnectionImpl.java

@Override
public int makeRequest(URL auth0Url, String accessToken) throws IOException {

    /* Open Connection */
    HttpsURLConnection connection = (HttpsURLConnection) auth0Url.openConnection();

    /* Provide 'credentials' */
    connection.setRequestProperty("Authorization", "Bearer " + accessToken);

    /* Retrieve response */
    responseCode = connection.getResponseCode();
    responseMessage = connection.getResponseMessage();
    if (responseCode == 200) {
        InputStream inputStr = connection.getInputStream();
        String encoding = connection.getContentEncoding() == null ? "UTF-8" : connection.getContentEncoding();
        jsonResponse = IOUtils.toString(inputStr, encoding);
        LOGGER.debug(String.format("Raw JSON Response:\n%s", jsonResponse));
    } else {/*ww w  . j a  v a  2s  .  co m*/
        LOGGER.error(String.format("Unable to read response: %d %s", responseCode, responseMessage));
    }
    return responseCode;
}

From source file:com.bytelightning.opensource.pokerface.HelloWorldScriptTest.java

@Test
public void testHelloWorld() throws IOException {
    URL obj = new URL("https://localhost:8443/helloWorlD.html"); // Intentional case mismatch
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("Accept-Language", "es, fr;q=0.8, en;q=0.7");
    int responseCode = con.getResponseCode();
    Assert.assertEquals("Valid reponse code", 200, responseCode);

    String contentType = con.getHeaderField("Content-Type");
    String charset = ScriptHelperImpl.GetCharsetFromContentType(contentType);
    Assert.assertTrue("Correct charset", charset.equalsIgnoreCase("utf-8"));

    try (Reader reader = new InputStreamReader(con.getInputStream(), charset)) {
        int aChar;
        StringBuilder sb = new StringBuilder();
        while ((aChar = reader.read()) != -1)
            sb.append((char) aChar);
        Assert.assertTrue("Acceptable language detected", sb.toString().contains("Hola mundo"));
    }/*from   w w w .  j  a  va  2  s. co m*/
}

From source file:com.github.jakz.geophoto.reverse.NominatimReverseGeocodingJAPI.java

private String getJSON(String urlString) throws IOException {
    URL obj = new URL(urlString);
    HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) (jack.ngi@gmail.com) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");

    InputStream is = conn.getInputStream();
    String json = IOUtils.toString(is, "UTF-8");
    is.close();//from w w w  .j a va  2 s  .  co m
    return json;
}

From source file:net.indialend.web.component.GCMComponent.java

public void setMessage(User user, String deactivate) {

    try {//from   w  w  w.  j av a  2 s . c om
        URL obj = new URL(serviceUrl);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Authorization", "key=" + API_KEY);

        String urlParameters = "{" + "   \"data\": {" + "     \"deactivate\": \"" + deactivate + "\"," + "   },"
                + "   \"to\": \"" + user.getGcmToken() + "\"" + " }";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.write(urlParameters.getBytes("UTF-8"));
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + serviceUrl);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        System.out.println(response.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.illusionaryone.GameWispAPIv1.java

@SuppressWarnings("UseSpecificCatch")
private static JSONObject readJsonFromUrl(String methodType, String urlAddress) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    OutputStream outputStream = null;
    URL urlRaw;//  www .java2  s .com
    HttpsURLConnection urlConn;
    String jsonText = "";

    if (sAccessToken.length() == 0) {
        if (!noAccessWarning) {
            com.gmt2001.Console.err.println(
                    "GameWispAPIv1: Attempting to use GameWisp API without key. Disabling the GameWisp module.");
            PhantomBot.instance().getDataStore().set("modules", "./handlers/gameWispHandler.js", "false");
            noAccessWarning = true;
        }
        JSONStringer jsonObject = new JSONStringer();
        return (new JSONObject(jsonObject.object().key("result").object().key("status").value(-1).endObject()
                .endObject().toString()));
    }

    try {
        urlRaw = new URL(urlAddress);
        urlConn = (HttpsURLConnection) urlRaw.openConnection();
        urlConn.setDoInput(true);
        urlConn.setRequestMethod(methodType);
        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");

        if (methodType.equals("POST")) {
            urlConn.setDoOutput(true);
            urlConn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        } else {
            urlConn.addRequestProperty("Content-Type", "application/json");
        }

        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, methodType, urlAddress, urlConn.getResponseCode(), "", "", jsonText);
    } catch (JSONException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "JSONException", ex.getMessage(),
                jsonText);
        com.gmt2001.Console.err
                .println("GameWispAPIv1::Bad JSON (" + urlAddress + "): " + jsonText.substring(0, 100) + "...");
    } catch (NullPointerException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "NullPointerException", ex.getMessage(),
                "");
        com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (MalformedURLException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "MalformedURLException", ex.getMessage(),
                "");
        com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (SocketTimeoutException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "SocketTimeoutException", ex.getMessage(),
                "");
        com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (IOException ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(), "");
        com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (Exception ex) {
        fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "Exception", ex.getMessage(), "");
        com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } finally {
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (IOException ex) {
                fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(),
                        "");
                com.gmt2001.Console.err
                        .println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
            }
    }

    return (jsonResult);
}

From source file:net.mms_projects.copy_it.server.push.android.GCMRunnable.java

public void run() {
    try {//from   w w  w  .j a  v a2 s .c  o  m
        URL url = new URL(GCM_URL);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod(POST);
        conn.setRequestProperty(CONTENT_TYPE, Page.ContentTypes.JSON_TYPE);
        conn.setRequestProperty(AUTHORIZATION, KEY);
        final String output_json = full.toString();
        System.err.println("Input json: " + output_json);
        conn.setRequestProperty(CONTENT_LENGTH, String.valueOf(output_json.length()));
        conn.setDoOutput(true);
        conn.setDoInput(true);
        DataOutputStream outputstream = new DataOutputStream(conn.getOutputStream());
        outputstream.writeBytes(output_json);
        outputstream.close();
        DataInputStream input = new DataInputStream(conn.getInputStream());
        StringBuilder builder = new StringBuilder(input.available());
        for (int c = input.read(); c != -1; c = input.read())
            builder.append((char) c);
        input.close();
        output = new JSONObject(builder.toString());
        System.err.println("Output json: " + output.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:io.fabric8.apiman.BearerTokenFilter.java

/**
 * Validates the bearer token with the kubernetes oapi and returns the username
 * if it is a valid token./*from   w ww  .jav a 2s. c  o  m*/
 * 
 * @param bearerHeader
 * @return username of the user to whom the token was issued to
 * @throws IOException - when the token is invalid, or oapi cannot be reached.
 */
protected String validateBearerToken(String bearerHeader) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    HttpsURLConnection con = (HttpsURLConnection) kubernetesOsapiUrl.openConnection();
    con.setRequestProperty("Authorization", bearerHeader);
    con.setConnectTimeout(10000);
    con.setReadTimeout(10000);
    con.setRequestProperty("Content-Type", "application/json");
    if (kubernetesTrustCert)
        TrustEverythingSSLTrustManager.trustAllSSLCertificates(con);
    con.connect();
    OAuthClientAuthorizationList userList = mapper.readValue(con.getInputStream(),
            OAuthClientAuthorizationList.class);
    String userName = userList.getItems().get(0).getMetadata().getName();
    return userName;
}

From source file:com.nadmm.airports.notams.NotamService.java

private void fetchNotams(String icaoCode, File notamFile) throws IOException {
    String params = String.format(NOTAM_PARAM, icaoCode);

    HttpsURLConnection conn = (HttpsURLConnection) NOTAM_URL.openConnection();
    conn.setRequestProperty("Connection", "close");
    conn.setDoInput(true);/*www. j  av a  2  s  . c  o m*/
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setConnectTimeout(30 * 1000);
    conn.setReadTimeout(30 * 1000);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US)");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", Integer.toString(params.length()));

    // Write out the form parameters as the request body
    OutputStream faa = conn.getOutputStream();
    faa.write(params.getBytes("UTF-8"));
    faa.close();

    int response = conn.getResponseCode();
    if (response == HttpURLConnection.HTTP_OK) {
        // Request was successful, parse the html to extract notams
        InputStream in = conn.getInputStream();
        ArrayList<String> notams = parseNotamsFromHtml(in);
        in.close();

        // Write the NOTAMS to the cache file
        BufferedOutputStream cache = new BufferedOutputStream(new FileOutputStream(notamFile));
        for (String notam : notams) {
            cache.write(notam.getBytes());
            cache.write('\n');
        }
        cache.close();
    }
}

From source file:org.jboss.aerogear.adm.TokenService.java

/**
 * Returns HttpsURLConnection that 'posts' the given payload to ADM.
 *//*from w  w w.j a v  a 2  s .co m*/
private HttpsURLConnection post(final String payload) throws Exception {

    final HttpsURLConnection conn = getHttpsURLConnection();
    conn.setDoOutput(true);
    conn.setUseCaches(false);

    // Set the content type .
    conn.setRequestProperty("content-type", APPLICATION_X_WWW_FORM_URLENCODED);
    conn.setRequestProperty("charset", UTF_8);

    conn.setRequestMethod("POST");

    OutputStream out = null;
    final byte[] bytes = payload.getBytes(UTF_8_CHARSET);
    try {
        out = conn.getOutputStream();
        out.write(bytes);
        out.flush();
    } finally {
        // in case something blows up, while writing
        // the payload, we wanna close the stream:
        if (out != null) {
            out.close();
        }
    }

    return conn;
}