Example usage for javax.net.ssl HttpsURLConnection setRequestMethod

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

Introduction

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

Prototype

public void setRequestMethod(String method) throws ProtocolException 

Source Link

Document

Set the method for the URL request, one of:
  • GET
  • POST
  • HEAD
  • OPTIONS
  • PUT
  • DELETE
  • TRACE
are legal, subject to protocol restrictions.

Usage

From source file:Activities.java

private String addData(String endpoint) {
    String data = null;// w w  w  .ja v  a 2  s .  co m
    try {
        // Construct request payload
        JSONObject attrObj = new JSONObject();
        attrObj.put("name", "URL");
        attrObj.put("value", "http://www.nvidia.com/game-giveaway");

        JSONArray attrArray = new JSONArray();
        attrArray.add(attrObj);

        TimeZone tz = TimeZone.getTimeZone("UTC");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
        df.setTimeZone(tz);
        String dateAsISO = df.format(new Date());

        // Required attributes
        JSONObject obj = new JSONObject();
        obj.put("leadId", "1001");
        obj.put("activityDate", dateAsISO);
        obj.put("activityTypeId", "1001");
        obj.put("primaryAttributeValue", "Game Giveaway");
        obj.put("attributes", attrArray);
        System.out.println(obj);

        // Make request
        URL url = new URL(endpoint);
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod("POST");
        urlConn.setAllowUserInteraction(false);
        urlConn.setDoOutput(true);
        urlConn.setRequestProperty("Content-type", "application/json");
        urlConn.setRequestProperty("accept", "application/json");
        urlConn.connect();
        OutputStream os = urlConn.getOutputStream();
        os.write(obj.toJSONString().getBytes());
        os.close();

        // Inspect response
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            System.out.println("Status: 200");
            InputStream inStream = urlConn.getInputStream();
            data = convertStreamToString(inStream);
            System.out.println(data);
        } else {
            System.out.println(responseCode);
            data = "Status:" + responseCode;
        }
    } catch (MalformedURLException e) {
        System.out.println("URL not valid.");
    } catch (IOException e) {
        System.out.println("IOException: " + e.getMessage());
        e.printStackTrace();
    }

    return data;
}

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  www .  j a  v  a2 s . com*/
}

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();//w w  w .  ja va 2  s .c om
    return json;
}

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;/*from  w ww . j  a v  a2  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.indialend.web.component.GCMComponent.java

public void setMessage(User user, String deactivate) {

    try {/*from  w w w  .  j  a v a2 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:it.bz.tis.integreen.carsharingbzit.api.ApiClient.java

public <T> T callWebService(ServiceRequest request, Class<T> clazz) throws IOException {

    request.request.technicalUser.username = this.user;
    request.request.technicalUser.password = this.password;

    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.NONE)
            .setVisibility(PropertyAccessor.IS_GETTER, Visibility.PUBLIC_ONLY)
            .setVisibility(PropertyAccessor.GETTER, Visibility.PUBLIC_ONLY)
            .setVisibility(PropertyAccessor.SETTER, Visibility.PUBLIC_ONLY);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    StringWriter sw = new StringWriter();
    mapper.writeValue(sw, request);//  w ww  . j  a  va  2  s. c  om

    String requestJson = sw.getBuffer().toString();

    logger.debug("callWebService(): jsonRequest:" + requestJson);

    URL url = new URL(this.endpoint);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    OutputStream out = conn.getOutputStream();
    out.write(requestJson.getBytes("UTF-8"));
    out.flush();
    int responseCode = conn.getResponseCode();

    InputStream input = conn.getInputStream();

    ByteArrayOutputStream data = new ByteArrayOutputStream();
    int len;
    byte[] buf = new byte[50000];
    while ((len = input.read(buf)) > 0) {
        data.write(buf, 0, len);
    }
    conn.disconnect();
    String jsonResponse = new String(data.toByteArray(), "UTF-8");

    if (responseCode != 200) {
        throw new IOException(jsonResponse);
    }

    logger.debug("callWebService(): jsonResponse:" + jsonResponse);

    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    T response = mapper.readValue(new StringReader(jsonResponse), clazz);

    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    sw = new StringWriter();
    mapper.writeValue(sw, response);
    logger.debug(
            "callWebService(): parsed response into " + response.getClass().getName() + ":" + sw.toString());

    return response;
}

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

public void run() {
    try {/* w  ww . j  ava  2s.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:org.openhab.binding.neato.internal.VendorVorwerk.java

@Override
public String executeRequest(String httpMethod, String url, Properties httpHeaders, InputStream content,
        String contentType, int timeout) throws IOException {

    URL requestUrl = new URL(url);
    HttpsURLConnection connection = (HttpsURLConnection) requestUrl.openConnection();
    applyNucleoSslConfiguration(connection);
    connection.setRequestMethod(httpMethod);
    for (String propName : httpHeaders.stringPropertyNames()) {
        connection.addRequestProperty(propName, httpHeaders.getProperty(propName));
    }/*from  w  w  w  .  j av a  2  s.co m*/
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    connection.setConnectTimeout(10000);
    connection.setReadTimeout(10000);
    content.reset();
    IOUtils.copy(content, connection.getOutputStream());

    java.io.InputStream is = connection.getInputStream();
    return IOUtils.toString(is);
}

From source file:com.wso2telco.MePinStatusRequest.java

public String call() {
    String allowStatus = null;//w w w  .  j av  a  2s  .  c  o m

    String clientId = configurationService.getDataHolder().getMobileConnectConfig().getSessionUpdaterConfig()
            .getMePinClientId();
    String url = configurationService.getDataHolder().getMobileConnectConfig().getSessionUpdaterConfig()
            .getMePinUrl();
    url = url + "?transaction_id=" + transactionId + "&client_id=" + clientId + "";
    if (log.isDebugEnabled()) {
        log.info("MePIN Status URL : " + url);
    }
    String authHeader = "Basic " + configurationService.getDataHolder().getMobileConnectConfig()
            .getSessionUpdaterConfig().getMePinAccessToken();

    try {
        HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();

        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization", authHeader);

        String resp = "";
        int statusCode = connection.getResponseCode();
        InputStream is;
        if ((statusCode == 200) || (statusCode == 201)) {
            is = connection.getInputStream();
        } else {
            is = connection.getErrorStream();
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String output;
        while ((output = br.readLine()) != null) {
            resp += output;
        }
        br.close();

        if (log.isDebugEnabled()) {
            log.debug("MePIN Status Response Code : " + statusCode + " " + connection.getResponseMessage());
            log.debug("MePIN Status Response : " + resp);
        }

        JsonObject responseJson = new JsonParser().parse(resp).getAsJsonObject();
        String respTransactionId = responseJson.getAsJsonPrimitive("transaction_id").getAsString();
        JsonPrimitive allowObject = responseJson.getAsJsonPrimitive("allow");

        if (allowObject != null) {
            allowStatus = allowObject.getAsString();
            if (Boolean.parseBoolean(allowStatus)) {
                allowStatus = "APPROVED";
                String sessionID = DatabaseUtils.getMePinSessionID(respTransactionId);
                DatabaseUtils.updateStatus(sessionID, allowStatus);
            }
        }

    } catch (IOException e) {
        log.error("Error while MePIN Status request" + e);
    } catch (SQLException e) {
        log.error("Error in connecting to DB" + e);
    }
    return allowStatus;
}

From source file:org.georchestra.console.ReCaptchaV2.java

/**
 *
 * @param url/*from   ww  w  .j a va  2 s .  c o  m*/
 * @param privateKey
 * @param gRecaptchaResponse
 *
 * @return true if validaded on server side by google, false in case of error or if an exception occurs
 */
public boolean isValid(String url, String privateKey, String gRecaptchaResponse) {
    boolean isValid = false;

    try {
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        // add request header
        con.setRequestMethod("POST");
        String postParams = "secret=" + privateKey + "&response=" + gRecaptchaResponse;

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(postParams);
        wr.flush();
        wr.close();

        if (LOG.isDebugEnabled()) {
            int responseCode = con.getResponseCode();
            LOG.debug("\nSending 'POST' request to URL : " + url);
            LOG.debug("Post parameters : " + postParams);
            LOG.debug("Response Code : " + responseCode);
        }

        // getResponse
        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
        LOG.debug(response.toString());

        JSONObject captchaResponse;
        try {
            captchaResponse = new JSONObject(response.toString());

            if (captchaResponse.getBoolean("success")) {
                isValid = true;
            } else {
                // Error in response
                LOG.info("The user response to recaptcha is not valid. The error message is '"
                        + captchaResponse.getString("error-codes")
                        + "' - see Error Code Reference at https://developers.google.com/recaptcha/docs/verify.");
            }
        } catch (JSONException e) {
            // Error in response
            LOG.error("Error while parsing ReCaptcha JSON response", e);
        }
    } catch (IOException e) {
        LOG.error("An error occured when trying to contact google captchaV2", e);
    }

    return isValid;
}