Example usage for java.net HttpURLConnection setRequestMethod

List of usage examples for java.net HttpURLConnection setRequestMethod

Introduction

In this page you can find the example usage for java.net HttpURLConnection 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:bluevia.SendSMS.java

public static void sendBlueViaSMS(String user_email, String phone_number, String sms_message) {
    try {/*from w ww.  j  a  va 2  s  . c o m*/

        Properties blueviaAccount = Util.getNetworkAccount(user_email, "BlueViaAccount");
        if (blueviaAccount != null) {
            String consumer_key = blueviaAccount.getProperty("BlueViaAccount.consumer_key");
            String consumer_secret = blueviaAccount.getProperty("BlueViaAccount.consumer_secret");
            String access_key = blueviaAccount.getProperty("BlueViaAccount.access_key");
            String access_secret = blueviaAccount.getProperty("BlueViaAccount.access_secret");

            com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate();

            OAuthConsumer consumer = (OAuthConsumer) new DefaultOAuthConsumer(consumer_key, consumer_secret);
            consumer.setMessageSigner(new HmacSha1MessageSigner());
            consumer.setTokenWithSecret(access_key, access_secret);

            URL apiURI = new URL("https://api.bluevia.com/services/REST/SMS/outbound/requests?version=v1");
            HttpURLConnection request = (HttpURLConnection) apiURI.openConnection();

            request.setRequestProperty("Content-Type", "application/json");
            request.setRequestMethod("POST");
            request.setDoOutput(true);

            consumer.sign(request);
            request.connect();

            String smsTemplate = "{\"smsText\": {\n  \"address\": {\"phoneNumber\": \"%s\"},\n  \"message\": \"%s\",\n  \"originAddress\": {\"alias\": \"%s\"},\n}}";
            String smsMsg = String.format(smsTemplate, phone_number, sms_message, access_key);

            OutputStream os = request.getOutputStream();
            os.write(smsMsg.getBytes());
            os.flush();

            int rc = request.getResponseCode();

            if (rc == HttpURLConnection.HTTP_CREATED)
                log.info(String.format("SMS sent to %s. Text: %s", phone_number, sms_message));
            else
                log.severe(String.format("Error %d sending SMS:%s\n", rc, request.getResponseMessage()));
        } else
            log.warning("BlueVia Account seems to be not configured!");

    } catch (Exception e) {
        log.severe(String.format("Exception sending SMS: %s", e.getMessage()));
    }
}

From source file:com.linkedin.pinot.controller.helix.ControllerTest.java

public static String sendPutRequest(String urlString, String payload) throws IOException {
    LOGGER.info("Sending PUT to " + urlString + " with payload " + payload);
    final long start = System.currentTimeMillis();
    final URL url = new URL(urlString);
    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);//from   w w  w.  j a va2  s  .  c o m
    conn.setRequestMethod("PUT");
    final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));

    writer.write(payload, 0, payload.length());
    writer.flush();

    final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    final StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

    final long stop = System.currentTimeMillis();

    LOGGER.info(" Time take for Request : " + urlString + " in ms:" + (stop - start));

    return sb.toString();
}

From source file:com.jts.rest.profileservice.utils.RestServiceHelper.java

/**
 * Makes a get request to the given url and returns the json object
 * @param sessionId//from  ww  w.j  a  v  a 2  s. c  om
 * @param url
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
public static JSONArray makeGetRequest(String sessionId, String url) throws MalformedURLException, IOException {
    URL endpoint = new URL(url);
    HttpURLConnection urlc = (HttpURLConnection) endpoint.openConnection();
    urlc.setRequestProperty("Authorization", "OAuth " + sessionId);
    urlc.setRequestMethod("GET");
    urlc.setDoOutput(true);
    String output = OauthHelperUtils.readInputStream(urlc.getInputStream());
    urlc.disconnect();
    Object json = JSONValue.parse(output);
    JSONArray jsonArr = (JSONArray) json;
    return jsonArr;
}

From source file:oneDrive.OneDriveAPI.java

public static String connectWithREST(String url, String method) throws IOException, ProtocolException {
    String newURL = "";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    // Connect with a REST Method: GET, DELETE, PUT
    con.setRequestMethod(method);
    //add request header
    con.setReadTimeout(20000);/*from   w  w w  .j a v a 2  s .com*/
    con.setConnectTimeout(20000);
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    if (method.equals(DELETE) || method.equals(PUT) || getSize)
        con.addRequestProperty("Authorization", "Bearer " + ACCESS_TOKEN);

    int responseCode = con.getResponseCode();
    // Read response
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    newURL = response.toString();

    return newURL;
}

From source file:Main.java

public static String httpPost(String urlStr, List<NameValuePair> params) {

    String paramsEncoded = "";
    if (params != null) {
        paramsEncoded = URLEncodedUtils.format(params, "UTF-8");
    }/*from  w  w w .j  a v a2s  .c o  m*/

    String result = null;
    URL url = null;
    HttpURLConnection connection = null;
    InputStreamReader in = null;
    try {
        url = new URL(urlStr);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Charset", "utf-8");
        DataOutputStream dop = new DataOutputStream(connection.getOutputStream());
        dop.writeBytes(paramsEncoded);
        dop.flush();
        dop.close();

        in = new InputStreamReader(connection.getInputStream());
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }
        result = strBuffer.toString();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    return result;
}

From source file:com.newrelic.agent.Deployments.java

static int recordDeployment(CommandLine cmd, AgentConfig config)/*  37:    */ throws Exception
/*  38:    */ {/*from  ww w .j  a v  a 2 s . c  o m*/
    /*  39: 35 */ String appName = config.getApplicationName();
    /*  40: 36 */ if (cmd.hasOption("appname")) {
        /*  41: 37 */ appName = cmd.getOptionValue("appname");
        /*  42:    */ }
    /*  43: 39 */ if (appName == null) {
        /*  44: 40 */ throw new IllegalArgumentException(
                "A deployment must be associated with an application.  Set app_name in newrelic.yml or specify the application name with the -appname switch.");
        /*  45:    */ }
    /*  46: 43 */ System.out.println("Recording a deployment for application " + appName);
    /*  47:    */
    /*  48: 45 */ String uri = "/deployments.xml";
    /*  49: 46 */ String payload = getDeploymentPayload(appName, cmd);
    /*  50: 47 */ String protocol = "http" + (config.isSSL() ? "s" : "");
    /*  51: 48 */ URL url = new URL(protocol, config.getApiHost(), config.getApiPort(), uri);
    /*  52:    */
    /*  53: 50 */ System.out.println(MessageFormat.format("Opening connection to {0}:{1}",
            new Object[] { config.getApiHost(), Integer.toString(config.getApiPort()) }));
    /*  54:    */
    /*  55:    */
    /*  56: 53 */ HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    /*  57: 54 */ conn.setRequestProperty("x-license-key", config.getLicenseKey());
    /*  58:    */
    /*  59: 56 */ conn.setRequestMethod("POST");
    /*  60: 57 */ conn.setConnectTimeout(10000);
    /*  61: 58 */ conn.setReadTimeout(10000);
    /*  62: 59 */ conn.setDoOutput(true);
    /*  63: 60 */ conn.setDoInput(true);
    /*  64:    */
    /*  65: 62 */ conn.setRequestProperty("Content-Length", Integer.toString(payload.length()));
    /*  66: 63 */ conn.setFixedLengthStreamingMode(payload.length());
    /*  67: 64 */ conn.getOutputStream().write(payload.getBytes());
    /*  68:    */
    /*  69: 66 */ int responseCode = conn.getResponseCode();
    /*  70: 67 */ if (responseCode < 300)
    /*  71:    */ {
        /*  72: 68 */ System.out.println("Deployment successfully recorded");
        /*  73:    */ }
    /*  74: 69 */ else if (responseCode == 401)
    /*  75:    */ {
        /*  76: 70 */ System.out.println(
                "Unable to notify New Relic of the deployment because of an authorization error.  Check your license key.");
        /*  77: 71 */ System.out.println("Response message: " + conn.getResponseMessage());
        /*  78:    */ }
    /*  79:    */ else
    /*  80:    */ {
        /*  81: 73 */ System.out.println("Unable to notify New Relic of the deployment");
        /*  82: 74 */ System.out.println("Response message: " + conn.getResponseMessage());
        /*  83:    */ }
    /*  84: 76 */ boolean isError = responseCode >= 300;
    /*  85: 77 */ if ((isError) || (config.isDebugEnabled()))
    /*  86:    */ {
        /*  87: 78 */ System.out.println("Response code: " + responseCode);
        /*  88: 79 */ InputStream inStream = isError ? conn.getErrorStream() : conn.getInputStream();
        /*  89: 81 */ if (inStream != null)
        /*  90:    */ {
            /*  91: 82 */ ByteArrayOutputStream output = new ByteArrayOutputStream();
            /*  92: 83 */ Streams.copy(inStream, output);
            /*  93:    */
            /*  94: 85 */ PrintStream out = isError ? System.err : System.out;
            /*  95:    */
            /*  96: 87 */ out.println(output);
            /*  97:    */ }
        /*  98:    */ }
    /*  99: 90 */ return responseCode;
    /* 100:    */ }

From source file:Main.java

/**
 * Make an HTTP request to the given URL and return a String as the response.
 *//*from w  ww .  j a va 2 s. c om*/
private static String makeHttpRequest(URL url) throws IOException {
    String jsonResponse = "";

    // If the URL is null, then return early.
    if (url == null) {
        return jsonResponse;
    }

    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        /*
        If the request was successful (response code 200),
        then read the input stream and parse the response.
         */
        if (urlConnection.getResponseCode() == 200) {
            inputStream = urlConnection.getInputStream();
            jsonResponse = readFromStream(inputStream);
        } else {
            //handle exception
        }
    } catch (IOException e) {
        //handle exception
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (inputStream != null) {
            inputStream.close();
        }
    }
    return jsonResponse;
}

From source file:com.andrious.btc.data.jsonUtils.java

private static HttpURLConnection urlConnect(String urlString) throws IOException {

    URL url = new URL(urlString);

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

    conn.setRequestMethod("GET");

    conn.setRequestProperty("Accept", "application/json");

    int response = conn.getResponseCode();

    if (response != HttpURLConnection.HTTP_OK) {

        if (!handleResponse(response, conn)) {

            throw new RuntimeException("Failed : HTTP error code : " + response);
        }//w w w .  j a  v  a  2  s  .c  o  m
    }

    return conn;
}

From source file:com.codelanx.codelanxlib.util.auth.UUIDFetcher.java

/**
 * Creates a connection object for requesting a single profile name
 * //from   w w  w . j av a  2s.c  o  m
 * @since 0.1.0
 * @version 0.1.0
 * 
 * @param name The name to request
 * @return The {@link HttpURLConnection} to Mojang's server
 * @throws IOException If there is a problem opening the stream, a malformed
 *                     URL, or if there is a ProtocolException
 */
private static HttpURLConnection createSingleProfileConnection(String name) throws IOException {
    URL url = new URL(String.format("https://api.mojang.com/users/profiles/minecraft/%s?at=0", name));
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    return connection;
}

From source file:it.unicaradio.android.gcm.GcmServerRpcCall.java

/**
 * @param url//from  ww w. j a  va  2  s .c  o  m
 * @param bytes
 * @return
 * @throws IOException
 * @throws ProtocolException
 */
private static HttpURLConnection setupConnection(URL url, byte[] bytes) throws IOException, ProtocolException {
    HttpURLConnection conn;
    conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(bytes.length);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
    return conn;
}