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:com.ds.kaixin.Util.java

/**
 * http//from w w  w .j  a va 2  s.  com
 * 
 * @param context
 *            
 * @param requestURL
 *            
 * @param httpMethod
 *            GET  POST
 * @param params
 *            key-valuekeyvalueString
 *            byte[]
 * @param photos
 *            key-value keyfilename
 *            valueInputStreambyte[]
 *            InputStreamopenUrl
 * @return JSON
 * @throws IOException
 */
public static String openUrl(Context context, String requestURL, String httpMethod, Bundle params,
        Map<String, Object> photos) throws IOException {

    OutputStream os;

    if (httpMethod.equals("GET")) {
        requestURL = requestURL + "?" + encodeUrl(params);
    }

    URL url = new URL(requestURL);
    HttpsURLConnection conn = (HttpsURLConnection) getConnection(context, url);

    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " KaixinAndroidSDK");

    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestProperty("Connection", "close");
    conn.setRequestProperty("Charsert", "UTF-8");

    if (!httpMethod.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        String BOUNDARY = Util.md5(String.valueOf(System.currentTimeMillis())); // 
        String endLine = "\r\n";

        conn.setRequestMethod("POST");

        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);

        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + BOUNDARY + endLine).getBytes());
        os.write((encodePostBody(params, BOUNDARY)).getBytes());
        os.write((endLine + "--" + BOUNDARY + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; name=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + BOUNDARY + endLine).getBytes());
            }
        }

        if (photos != null && !photos.isEmpty()) {

            for (String key : photos.keySet()) {

                Object obj = photos.get(key);
                if (obj instanceof InputStream) {
                    InputStream is = (InputStream) obj;
                    try {
                        os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\""
                                + endLine).getBytes());
                        os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes());
                        byte[] data = new byte[UPLOAD_BUFFER_SIZE];
                        int nReadLength = 0;
                        while ((nReadLength = is.read(data)) != -1) {
                            os.write(data, 0, nReadLength);
                        }
                        os.write((endLine + "--" + BOUNDARY + endLine).getBytes());
                    } finally {
                        try {
                            if (null != is) {
                                is.close();
                            }
                        } catch (Exception e) {
                            Log.e(LOG_TAG, "Exception on closing input stream", e);
                        }
                    }
                } else if (obj instanceof byte[]) {
                    byte[] byteArray = (byte[]) obj;
                    os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine)
                            .getBytes());
                    os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes());
                    os.write(byteArray);
                    os.write((endLine + "--" + BOUNDARY + endLine).getBytes());
                } else {
                    Log.e(LOG_TAG, "");
                }
            }
        }

        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        response = read(conn.getErrorStream());
    }
    return response;
}

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);// w w  w  .j  av a  2 s .com
    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 ww w  .  java  2  s.com*/
        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:de.btobastian.javacord.entities.impl.ImplCustomEmoji.java

@Override
public Future<byte[]> getEmojiAsByteArray(FutureCallback<byte[]> callback) {
    ListenableFuture<byte[]> future = api.getThreadPool().getListeningExecutorService()
            .submit(new Callable<byte[]>() {
                @Override//from ww w .ja v  a 2s.  c  om
                public byte[] call() throws Exception {
                    logger.debug("Trying to get emoji {} from server {}", ImplCustomEmoji.this, server);
                    URL url = getImageUrl();
                    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
                    conn.setRequestProperty("User-Agent", Javacord.USER_AGENT);
                    InputStream in = new BufferedInputStream(conn.getInputStream());
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    byte[] buf = new byte[1024];
                    int n;
                    while (-1 != (n = in.read(buf))) {
                        out.write(buf, 0, n);
                    }
                    out.close();
                    in.close();
                    byte[] emoji = out.toByteArray();
                    logger.debug("Got emoji {} from server {} (size: {})", ImplCustomEmoji.this, server,
                            emoji.length);
                    return emoji;
                }
            });
    if (callback != null) {
        Futures.addCallback(future, callback);
    }
    return future;
}

From source file:com.microsoft.valda.oms.OmsAppender.java

private void sendLog(LoggingEvent event)
        throws NoSuchAlgorithmException, InvalidKeyException, IOException, HTTPException {
    //create JSON message
    JSONObject obj = new JSONObject();
    obj.put("LOGBACKLoggerName", event.getLoggerName());
    obj.put("LOGBACKLogLevel", event.getLevel().toString());
    obj.put("LOGBACKMessage", event.getFormattedMessage());
    obj.put("LOGBACKThread", event.getThreadName());
    if (event.getCallerData() != null && event.getCallerData().length > 0) {
        obj.put("LOGBACKCallerData", event.getCallerData()[0].toString());
    } else {/*from  w w  w .  j a  v a 2s.c  o  m*/
        obj.put("LOGBACKCallerData", "");
    }
    if (event.getThrowableProxy() != null) {
        obj.put("LOGBACKStackTrace", ThrowableProxyUtil.asString(event.getThrowableProxy()));
    } else {
        obj.put("LOGBACKStackTrace", "");
    }
    if (inetAddress != null) {
        obj.put("LOGBACKIPAddress", inetAddress.getHostAddress());
    } else {
        obj.put("LOGBACKIPAddress", "0.0.0.0");
    }
    String json = obj.toJSONString();

    String Signature = "";
    String encodedHash = "";
    String url = "";

    // Todays date input for OMS Log Analytics
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    String timeNow = dateFormat.format(calendar.getTime());

    // String for signing the key
    String stringToSign = "POST\n" + json.length() + "\napplication/json\nx-ms-date:" + timeNow + "\n/api/logs";
    byte[] decodedBytes = Base64.decodeBase64(sharedKey);
    Mac hasher = Mac.getInstance("HmacSHA256");
    hasher.init(new SecretKeySpec(decodedBytes, "HmacSHA256"));
    byte[] hash = hasher.doFinal(stringToSign.getBytes());

    encodedHash = DatatypeConverter.printBase64Binary(hash);
    Signature = "SharedKey " + customerId + ":" + encodedHash;

    url = "https://" + customerId + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01";
    URL objUrl = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) objUrl.openConnection();
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Log-Type", logType);
    con.setRequestProperty("x-ms-date", timeNow);
    con.setRequestProperty("Authorization", Signature);

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(json);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    if (responseCode != 200) {
        throw new HTTPException(responseCode);
    }
}

From source file:org.wso2.carbon.integration.common.tests.JaggeryServerTest.java

/**
 * Sending the request and getting the response
 * @param Uri - request url/*w ww  .  j  a  va 2 s . c o  m*/
 * @param append - append request parameters
 * @throws IOException
 */
private HttpsResponse getRequest(String Uri, String requestParameters, boolean append) throws IOException {
    if (Uri.startsWith("https://")) {
        String urlStr = Uri;
        if (requestParameters != null && requestParameters.length() > 0) {
            if (append) {
                urlStr += "?" + requestParameters;
            } else {
                urlStr += requestParameters;
            }
        }
        URL url = new URL(urlStr);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        conn.setReadTimeout(30000);
        conn.connect();
        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } catch (IOException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:org.talend.components.marketo.runtime.client.MarketoBulkExecClient.java

public void executeDownloadFileRequest(File filename) throws MarketoException {
    String err;//ww  w  .  j  av a  2  s  .  c  o  m
    try {
        URL url = new URL(current_uri.toString());
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod("GET");
        urlConn.setRequestProperty("accept", "text/json");
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            InputStream inStream = urlConn.getInputStream();
            FileUtils.copyInputStreamToFile(inStream, filename);
        } else {
            err = String.format("Download failed for %s. Status: %d", filename, responseCode);
            throw new MarketoException(REST, err);
        }
    } catch (IOException e) {
        err = String.format("Download failed for %s. Cause: %s", filename, e.getMessage());
        LOG.error(err);
        throw new MarketoException(REST, err);
    }
}

From source file:org.jembi.rhea.rapidsms.GenerateORU_R01Alert.java

public String callQueryFacility(String msg)
        throws IOException, TransformerFactoryConfigurationError, TransformerException {

    // Setup connection
    URL url = new URL(hostname + "/ws/rest/v1/alerts");
    System.out.println("full url " + url);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);/*from  w  w  w.jav  a2s  . co m*/
    conn.setRequestMethod("POST");
    conn.setDoInput(true);

    // This is important to get the connection to use our trusted
    // certificate
    conn.setSSLSocketFactory(sslFactory);

    addHTTPBasicAuthProperty(conn);
    // conn.setConnectTimeout(timeOut);
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    log.error("body" + msg);
    out.write(msg);
    out.close();
    conn.connect();

    // Test response code
    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }

    String result = convertInputStreamToString(conn.getInputStream());
    conn.disconnect();

    return result;
}

From source file:org.wso2.carbon.appmgt.sample.deployer.http.HttpHandler.java

/**
 * This method is used to do a https post request
 *
 * @param url         request url//  w  w  w .ja  v  a  2  s .c  o m
 * @param payload     Content of the post request
 * @param sessionId   sessionId for authentication
 * @param contentType content type of the post request
 * @return response
 * @throws java.io.IOException - Throws this when failed to fulfill a https post request
 */
public String doPostHttps(String url, String payload, String sessionId, String contentType) throws IOException {
    URL obj = new URL(url);

    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    if (!sessionId.equals("")) {
        con.setRequestProperty("Cookie", "JSESSIONID=" + sessionId);
    }
    if (!contentType.equals("")) {
        con.setRequestProperty("Content-Type", contentType);
    }
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(payload);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    if (responseCode == 200) {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        if (sessionId.equals("")) {
            String session_id = response.substring((response.lastIndexOf(":") + 3),
                    (response.lastIndexOf("}") - 2));
            return session_id;
        } else if (sessionId.equals("header")) {
            return con.getHeaderField("Set-Cookie");
        }

        return response.toString();
    }
    return null;
}

From source file:com.starr.smartbuilds.service.DataService.java

public void getItemsDataFromRiotAPI() throws IOException, ParseException {
    String line;//from  w w  w. j  a v a  2s.c o m
    String result = "";
    URL url = new URL("https://global.api.pvp.net/api/lol/static-data/euw/v1.2/item?itemListData=tags&api_key="
            + Constants.API_KEY);
    //Get connection
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("GET");

    int responseCode = conn.getResponseCode();
    System.out.println("resp:" + responseCode);
    System.out.println("resp msg:" + conn.getResponseMessage());

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    System.out.println("BUFFER----");
    while ((line = br.readLine()) != null) {
        result += line;
    }

    conn.disconnect();
    getItemsFromData(result);
}