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:com.wso2telco.MePinStatusRequest.java

public String call() {
    String allowStatus = null;// w w w  .  j a v  a  2 s .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:Activities.java

private String addData(String endpoint) {
    String data = null;/*from www .  j  a v a2  s .  c o  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:org.sakaiproject.contentreview.turnitin.util.TurnitinAPIUtil.java

public static InputStream callTurnitinReturnInputStream(String apiURL, Map<String, Object> parameters,
        String secretKey, int timeout, Proxy proxy, boolean isMultipart)
        throws TransientSubmissionException, SubmissionException {
    InputStream togo = null;//from   ww  w . j  a  v a 2 s.  c o  m

    StringBuilder apiDebugSB = new StringBuilder();

    if (!parameters.containsKey("fid")) {
        throw new IllegalArgumentException("You must to include a fid in the parameters");
    }

    //if (!parameters.containsKey("gmttime")) {
    parameters.put("gmtime", getGMTime());
    //}

    /**
     * Some debug logging
     */
    if (log.isDebugEnabled()) {
        Set<Entry<String, Object>> ets = parameters.entrySet();
        Iterator<Entry<String, Object>> it = ets.iterator();
        while (it.hasNext()) {
            Entry<String, Object> entr = it.next();
            log.debug("Paramater entry: " + entr.getKey() + ": " + entr.getValue());
        }
    }

    List<String> sortedkeys = new ArrayList<String>();
    sortedkeys.addAll(parameters.keySet());

    String md5 = buildTurnitinMD5(parameters, secretKey, sortedkeys);

    HttpsURLConnection connection;
    String boundary = "";
    try {
        connection = fetchConnection(apiURL, timeout, proxy);
        connection.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        if (isMultipart) {
            Random rand = new Random();
            //make up a boundary that should be unique
            boundary = Long.toString(rand.nextLong(), 26) + Long.toString(rand.nextLong(), 26)
                    + Long.toString(rand.nextLong(), 26);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        }

        log.debug("HTTPS Connection made to Turnitin");

        OutputStream outStream = connection.getOutputStream();

        if (isMultipart) {
            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("Starting Multipart TII CALL:\n");
            }
            for (int i = 0; i < sortedkeys.size(); i++) {
                if (parameters.get(sortedkeys.get(i)) instanceof ContentResource) {
                    ContentResource resource = (ContentResource) parameters.get(sortedkeys.get(i));
                    outStream.write(
                            ("--" + boundary + "\r\nContent-Disposition: form-data; name=\"pdata\"; filename=\""
                                    + resource.getId() + "\"\r\n" + "Content-Type: " + resource.getContentType()
                                    + "\r\ncontent-transfer-encoding: binary" + "\r\n\r\n").getBytes());
                    //TODO this loads the doc into memory rather use the stream method
                    byte[] content = resource.getContent();
                    if (content == null) {
                        throw new SubmissionException("zero length submission!");
                    }
                    outStream.write(content);
                    outStream.write("\r\n".getBytes("UTF-8"));
                    if (apiTraceLog.isDebugEnabled()) {
                        apiDebugSB.append(sortedkeys.get(i));
                        apiDebugSB.append(" = ContentHostingResource: ");
                        apiDebugSB.append(resource.getId());
                        apiDebugSB.append("\n");
                    }
                } else {
                    if (apiTraceLog.isDebugEnabled()) {
                        apiDebugSB.append(sortedkeys.get(i));
                        apiDebugSB.append(" = ");
                        apiDebugSB.append(parameters.get(sortedkeys.get(i)).toString());
                        apiDebugSB.append("\n");
                    }
                    outStream.write(encodeParam(sortedkeys.get(i), parameters.get(sortedkeys.get(i)).toString(),
                            boundary).getBytes());
                }
            }
            outStream.write(encodeParam("md5", md5, boundary).getBytes());
            outStream.write(("--" + boundary + "--").getBytes());

            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("md5 = ");
                apiDebugSB.append(md5);
                apiDebugSB.append("\n");
                apiTraceLog.debug(apiDebugSB.toString());
            }
        } else {
            writeBytesToOutputStream(outStream, sortedkeys.get(0), "=",
                    parameters.get(sortedkeys.get(0)).toString());
            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("Starting TII CALL:\n");
                apiDebugSB.append(sortedkeys.get(0));
                apiDebugSB.append(" = ");
                apiDebugSB.append(parameters.get(sortedkeys.get(0)).toString());
                apiDebugSB.append("\n");
            }

            for (int i = 1; i < sortedkeys.size(); i++) {
                writeBytesToOutputStream(outStream, "&", sortedkeys.get(i), "=",
                        parameters.get(sortedkeys.get(i)).toString());
                if (apiTraceLog.isDebugEnabled()) {
                    apiDebugSB.append(sortedkeys.get(i));
                    apiDebugSB.append(" = ");
                    apiDebugSB.append(parameters.get(sortedkeys.get(i)).toString());
                    apiDebugSB.append("\n");
                }
            }

            writeBytesToOutputStream(outStream, "&md5=", md5);
            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("md5 = ");
                apiDebugSB.append(md5);
                apiTraceLog.debug(apiDebugSB.toString());
            }
        }

        outStream.close();

        togo = connection.getInputStream();
    } catch (IOException t) {
        log.error("IOException making turnitin call.", t);
        throw new TransientSubmissionException("IOException making turnitin call.", t);
    } catch (ServerOverloadException t) {
        throw new TransientSubmissionException("Unable to submit the content data from ContentHosting", t);
    }

    return togo;

}

From source file:com.microsoft.onenote.pickerlib.ApiRequestAsyncTask.java

private JSONObject getJSONResponse(String endpoint) throws Exception {
    HttpsURLConnection mUrlConnection = (HttpsURLConnection) (new URL(endpoint)).openConnection();
    mUrlConnection.setRequestProperty("User-Agent",
            System.getProperty("http.agent") + " Android OneNotePicker");
    if (mAccessToken != null) {
        mUrlConnection.setRequestProperty("Authorization", "Bearer " + mAccessToken);
    }/*from  w  ww . ja  va  2  s . c om*/
    mUrlConnection.connect();

    int responseCode = mUrlConnection.getResponseCode();
    String responseMessage = mUrlConnection.getResponseMessage();
    String responseBody = null;
    boolean responseIsJson = mUrlConnection.getContentType().contains("application/json");
    JSONObject responseObject;
    if (responseCode == HttpsURLConnection.HTTP_UNAUTHORIZED) {
        mUrlConnection.disconnect();
        throw new ApiException(Integer.toString(responseCode) + " " + responseMessage, null,
                "Invalid or missing access token.", null);
    }
    if (responseIsJson) {
        InputStream is = null;
        try {
            if (responseCode == HttpsURLConnection.HTTP_INTERNAL_ERROR) {
                is = mUrlConnection.getErrorStream();
            } else {
                is = mUrlConnection.getInputStream();
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line = null;
            String lineSeparator = System.getProperty("line.separator");
            StringBuffer buffer = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
                buffer.append(lineSeparator);
            }
            responseBody = buffer.toString();
        } finally {
            if (is != null) {
                is.close();
            }
            mUrlConnection.disconnect();
        }

        responseObject = new JSONObject(responseBody);
    } else {
        throw new ApiException(Integer.toString(responseCode) + " " + responseMessage, null,
                "Unrecognized server response", null);
    }

    return responseObject;
}

From source file:org.mule.modules.wechat.common.HttpsConnection.java

public Map<String, Object> get(String httpsURL) throws Exception {
    // Setup connection
    String result = "";
    URL url = new URL(httpsURL);
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("Content-Type", "application/json; encoding=utf-8");

    // Call wechat
    InputStream ins = con.getInputStream();
    InputStreamReader isr = new InputStreamReader(ins, "UTF-8");
    BufferedReader in = new BufferedReader(isr);

    // Read result
    String inputLine;/*from   w  w w  .j  av  a 2  s .c  o m*/
    StringBuilder sb = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        sb.append((new JSONObject(inputLine)).toString());
    }
    result = sb.toString();
    in.close();

    // Convert JSON string to Map
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue(result, new TypeReference<Map<String, Object>>() {
    });

    return map;
}

From source file:org.mule.modules.wechat.common.HttpsConnection.java

public Map<String, Object> post(String httpsURL, String json) throws Exception {
    // Setup connection
    String result = "";
    URL url = new URL(httpsURL);
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json; encoding=utf-8");
    con.setDoOutput(true);//from ww  w.j  a v  a  2  s  .c o m
    OutputStream ops = con.getOutputStream();
    ops.write(json.getBytes("UTF-8"));
    ops.flush();
    ops.close();

    // Call wechat
    InputStream ins = con.getInputStream();
    InputStreamReader isr = new InputStreamReader(ins, "UTF-8");
    BufferedReader in = new BufferedReader(isr);

    // Read result
    String inputLine;
    StringBuilder sb = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        sb.append((new JSONObject(inputLine)).toString());
    }
    result = sb.toString();
    in.close();

    // Convert JSON string to Map
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue(result, new TypeReference<Map<String, Object>>() {
    });

    return map;
}

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

/**
 * Returns HttpsURLConnection that 'posts' the given payload to ADM.
 *//*from   ww  w .  ja v  a  2 s  .  c o  m*/
private HttpsURLConnection post(final String registrationId, final String payload) throws Exception {

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

    // Set the content type and accept headers.
    conn.setRequestProperty("content-type", "application/json");
    conn.setRequestProperty("accept", "application/json");
    conn.setRequestProperty("X-Amzn-Type-Version ", "com.amazon.device.messaging.ADMMessage@1.0");
    conn.setRequestProperty("X-Amzn-Accept-Type", "com.amazon.device.messaging.ADMSendResult@1.0");

    conn.setRequestMethod("POST");

    // Add the authorization token as a header.
    conn.setRequestProperty("Authorization", "Bearer " + accessToken);

    OutputStream out = null;
    final byte[] bytes = payload.getBytes(UTF_8);
    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;
}

From source file:org.aankor.animenforadio.api.WebsiteGate.java

private JSONObject request(EnumSet<Subscription> subscriptions) throws IOException, JSONException {
    // fetchCookies();

    // TODO: fetch peice by piece
    URL url = new URL("https://www.animenfo.com/radio/index.php?t=" + (new Date()).getTime());
    // URL url = new URL("http://192.168.0.2:12345/");
    String body = "{\"ajaxcombine\":true,\"pages\":[{\"uid\":\"nowplaying\",\"page\":\"nowplaying.php\",\"args\":{\"mod\":\"playing\"}}"
            + ",{\"uid\":\"queue\",\"page\":\"nowplaying.php\",\"args\":{\"mod\":\"queue\"}},{\"uid\":\"recent\",\"page\":\"nowplaying.php\",\"args\":{\"mod\":\"recent\"}}]}";
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Accept", "application/json");
    con.setRequestProperty("Accept-Encoding", "gzip, deflate");
    con.setRequestProperty("Content-Type", "application/json");
    if (!phpSessID.equals(""))
        con.setRequestProperty("Cookie", "PHPSESSID=" + phpSessID);
    con.setRequestProperty("Host", "www.animenfo.com");
    con.setRequestProperty("Referer", "https://www.animenfo.com/radio/nowplaying.php");
    con.setRequestProperty("User-Agent",
            "Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.1.0");
    // con.setUseCaches (false);
    con.setDoInput(true);/*from w ww.  j  a  va2  s.c o  m*/
    con.setDoOutput(true);

    //Send request

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(body);
    wr.flush();
    wr.close();
    InputStream is = con.getInputStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    String line;
    StringBuilder response = new StringBuilder();
    while ((line = rd.readLine()) != null) {
        response.append(line);
    }
    rd.close();

    // updateCookies(con);
    return new JSONObject(response.toString());

}

From source file:hudson.plugins.boundary.Boundary.java

public void sendEvent(AbstractBuild<?, ?> build, BuildListener listener) throws IOException {
    final HashMap<String, Object> event = new HashMap<String, Object>();
    event.put("fingerprintFields", Arrays.asList("build name"));

    final Map<String, String> source = new HashMap<String, String>();
    String hostname = "localhost";

    try {/*from  w w  w. j  av a2 s . c o  m*/
        hostname = java.net.InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        listener.getLogger().println("host lookup exception: " + e);
    }

    source.put("ref", hostname);
    source.put("type", "jenkins");
    event.put("source", source);

    final Map<String, String> properties = new HashMap<String, String>();
    properties.put("build status", build.getResult().toString());
    properties.put("build number", build.getDisplayName());
    properties.put("build name", build.getProject().getName());
    event.put("properties", properties);

    event.put("title",
            String.format("Jenkins Build Job - %s - %s", build.getProject().getName(), build.getDisplayName()));

    if (Result.SUCCESS.equals(build.getResult())) {
        event.put("severity", "INFO");
        event.put("status", "CLOSED");
    } else {
        event.put("severity", "WARN");
        event.put("status", "OPEN");
    }

    final String url = String.format("https://api.boundary.com/%s/events", this.id);
    final HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
    conn.setConnectTimeout(30000);
    conn.setReadTimeout(30000);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    final String authHeader = "Basic " + new String(Base64.encodeBase64((token + ":").getBytes(), false));
    conn.setRequestProperty("Authorization", authHeader);
    conn.setDoInput(true);
    conn.setDoOutput(true);

    InputStream is = null;
    OutputStream os = null;
    try {
        os = conn.getOutputStream();
        OBJECT_MAPPER.writeValue(os, event);
        os.flush();
        is = conn.getInputStream();
    } finally {
        close(is);
        close(os);
    }

    final int responseCode = conn.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_CREATED) {
        listener.getLogger().println("Invalid HTTP response code from Boundary API: " + responseCode);
    } else {
        String location = conn.getHeaderField("Location");
        if (location.startsWith("http:")) {
            location = "https" + location.substring(4);
        }
        listener.getLogger().println("Created Boundary Event: " + location);
    }
}

From source file:com.fastbootmobile.twofactorauthdemo.MainActivity.java

protected void registerWithBackend() {

    final SharedPreferences pref = this.getSharedPreferences(OwnPushClient.PREF_PUSH, Context.MODE_PRIVATE);

    Thread httpThread = new Thread(new Runnable() {

        private String TAG = "httpThread";
        private String ENDPOINT = "https://otp.demo.ownpush.com/push/register";

        @Override/*from   w w  w .j av a  2  s  .c  o  m*/
        public void run() {
            URL urlObj;

            try {
                urlObj = new URL(ENDPOINT);

                String install_id = pref.getString(OwnPushClient.PREF_PUBLIC_KEY, null);

                if (install_id == null) {
                    return;
                }

                String mPostData = "push_id=" + install_id;
                HttpsURLConnection con = (HttpsURLConnection) urlObj.openConnection();

                con.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
                con.setRequestProperty("Accept", "*/*");
                con.setDoInput(true);
                con.setRequestMethod("POST");
                con.getOutputStream().write(mPostData.getBytes());
                con.connect();
                int http_status = con.getResponseCode();

                if (http_status != 200) {
                    Log.e(TAG, "ERROR IN HTTP REPONSE : " + http_status);
                    return;
                }

                InputStream stream;
                stream = con.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(stream));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();
                String data = sb.toString();

                if (data.contains("device_uid")) {
                    JSONObject json = new JSONObject(data);
                    String device_id = json.getString("device_uid");
                    pref.edit().putString("device_uid", device_id).commit();
                    Log.d(TAG, "GOT DEVICE UID OF " + device_id);

                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            updateUI();
                        }
                    });

                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    httpThread.start();
}