Example usage for java.net HttpURLConnection getRequestMethod

List of usage examples for java.net HttpURLConnection getRequestMethod

Introduction

In this page you can find the example usage for java.net HttpURLConnection getRequestMethod.

Prototype

public String getRequestMethod() 

Source Link

Document

Get the request method.

Usage

From source file:Main.java

public static void main(String args[]) throws Exception {
    URL url = new URL("http://www.google.com");
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();

    System.out.println("Request method is " + httpCon.getRequestMethod());

}

From source file:GetURLInfo.java

/** Use the URLConnection class to get info about the URL */
public static void printinfo(URL url) throws IOException {
    URLConnection c = url.openConnection(); // Get URLConnection from URL
    c.connect(); // Open a connection to URL

    // Display some information about the URL contents
    System.out.println("  Content Type: " + c.getContentType());
    System.out.println("  Content Encoding: " + c.getContentEncoding());
    System.out.println("  Content Length: " + c.getContentLength());
    System.out.println("  Date: " + new Date(c.getDate()));
    System.out.println("  Last Modified: " + new Date(c.getLastModified()));
    System.out.println("  Expiration: " + new Date(c.getExpiration()));

    // If it is an HTTP connection, display some additional information.
    if (c instanceof HttpURLConnection) {
        HttpURLConnection h = (HttpURLConnection) c;
        System.out.println("  Request Method: " + h.getRequestMethod());
        System.out.println("  Response Message: " + h.getResponseMessage());
        System.out.println("  Response Code: " + h.getResponseCode());
    }//  ww w.jav  a2 s.co m
}

From source file:org.rapidcontext.app.plugin.http.HttpPostProcedure.java

/**
 * Logs the HTTP request to the procedure call context.
 *
 * @param cx             the procedure call context
 * @param con            the HTTP connection
 * @param data           the HTTP request data
 *///w  w w.  j a v  a  2 s  . c  o m
private static void logRequest(CallContext cx, HttpURLConnection con, String data) {

    cx.log("HTTP " + con.getRequestMethod() + " " + con.getURL());
    Iterator iter = con.getRequestProperties().keySet().iterator();
    while (iter.hasNext()) {
        String key = (String) iter.next();
        cx.log("  " + key + ": " + con.getRequestProperty(key));
    }
    if (data != null) {
        cx.log(data);
    }
}

From source file:net.ftb.util.AppUtils.java

public static void debugConnection(URLConnection c, boolean forceDebug) {
    if (Settings.getSettings().getDebugLauncher() || forceDebug) {
        if (!(c instanceof HttpURLConnection)) {
            Logger.logDebug("Something bad just happened.");
        }//  w  ww  .  ja  v a  2 s. c  o  m

        // for IP we need to use reflection or pass url here and rely on dns caching
        // ref: https://community.oracle.com/thread/2149226

        HttpURLConnection conn = (HttpURLConnection) c;
        int responseCode;
        try {
            responseCode = conn.getResponseCode();
        } catch (Exception e) {
            responseCode = -1;
            Logger.logDebug("failed", e);
        }

        Logger.logDebug("Request type: " + conn.getRequestMethod());
        Logger.logDebug("URL: " + conn.getURL());
        Logger.logDebug("Response code: " + responseCode);
        Logger.logDebug("Headers:\n" + AppUtils.MapListToString(conn.getHeaderFields()));
        Logger.logDebug("Message body\n" + AppUtils.ConnectionToString(conn));
        if (conn.getURL().toString().contains("ftb.cursecdn.com")) {
            DownloadUtils.CloudFlareInspector("http://ftb.cursecdn.com/", true);
        }
    }
}

From source file:com.facebook.GraphRequestTest.java

@Test
public void testSingleGetToHttpRequest() throws Exception {
    GraphRequest requestMe = new GraphRequest(null, "TourEiffel");
    HttpURLConnection connection = GraphRequest.toHttpConnection(requestMe);

    assertTrue(connection != null);/*w  ww. j  a va 2s  . c  o m*/

    assertEquals("GET", connection.getRequestMethod());
    assertEquals("/" + ServerProtocol.getAPIVersion() + "/TourEiffel", connection.getURL().getPath());

    assertTrue(connection.getRequestProperty("User-Agent").startsWith("FBAndroidSDK"));

    Uri uri = Uri.parse(connection.getURL().toString());
    assertEquals("android", uri.getQueryParameter("sdk"));
    assertEquals("json", uri.getQueryParameter("format"));
}

From source file:org.apache.hadoop.fs.azure.SelfThrottlingIntercept.java

public void responseReceived(ResponseReceivedEvent event) {
    RequestResult result = event.getRequestResult();
    Date startDate = result.getStartDate();
    Date stopDate = result.getStopDate();
    long elapsed = stopDate.getTime() - startDate.getTime();

    synchronized (this) {
        this.lastE2Elatency = elapsed;
    }//from  ww w .j av a2 s.c  o  m

    if (LOG.isDebugEnabled()) {
        int statusCode = result.getStatusCode();
        String etag = result.getEtag();
        HttpURLConnection urlConnection = (HttpURLConnection) event.getConnectionObject();
        int contentLength = urlConnection.getContentLength();
        String requestMethod = urlConnection.getRequestMethod();
        long threadId = Thread.currentThread().getId();
        LOG.debug(String.format(
                "SelfThrottlingIntercept:: ResponseReceived: threadId=%d, Status=%d, Elapsed(ms)=%d, ETAG=%s, contentLength=%d, requestMethod=%s",
                threadId, statusCode, elapsed, etag, contentLength, requestMethod));
    }
}

From source file:com.twitter.sdk.android.core.internal.oauth.OAuth1aServiceTest.java

@Test
public void testSignRequest() throws MalformedURLException {
    final TwitterAuthConfig config = new TwitterAuthConfig("consumerKey", "consumerSecret");
    final TwitterAuthToken accessToken = new TwitterAuthToken("token", "tokenSecret");

    final HttpURLConnection connection = mock(HttpURLConnection.class);
    when(connection.getRequestMethod()).thenReturn("GET");
    when(connection.getURL()).thenReturn(new URL("https://api.twitter.com/1.1/statuses/home_timeline.json"));

    OAuth1aService.signRequest(config, accessToken, connection, null);
    verify(connection).setRequestProperty(eq(HttpRequest.HEADER_AUTHORIZATION), any(String.class));

    // TODO: Make it so that nonce and timestamp can be specified for testing puproses?
}

From source file:org.apache.hadoop.fs.azure.SelfThrottlingIntercept.java

public void sendingRequest(SendingRequestEvent sendEvent) {
    long lastLatency;
    boolean operationIsRead; // for logging
    synchronized (this) {

        lastLatency = this.lastE2Elatency;
    }/*from  ww  w  .  java 2s.co  m*/

    float sleepMultiple;
    HttpURLConnection urlConnection = (HttpURLConnection) sendEvent.getConnectionObject();

    // Azure REST API never uses POST, so PUT is a sufficient test for an
    // upload.
    if (urlConnection.getRequestMethod().equalsIgnoreCase("PUT")) {
        operationIsRead = false;
        sleepMultiple = (1 / writeFactor) - 1;
    } else {
        operationIsRead = true;
        sleepMultiple = (1 / readFactor) - 1;
    }

    long sleepDuration = (long) (sleepMultiple * lastLatency);
    if (sleepDuration < 0) {
        sleepDuration = 0;
    }

    if (sleepDuration > 0) {
        try {
            // Thread.sleep() is not exact but it seems sufficiently accurate for
            // our needs. If needed this could become a loop of small waits that
            // tracks actual
            // elapsed time.
            Thread.sleep(sleepDuration);
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
        }

        // reset to avoid counting the sleep against request latency
        sendEvent.getRequestResult().setStartDate(new Date());
    }

    if (LOG.isDebugEnabled()) {
        boolean isFirstRequest = (lastLatency == 0);
        long threadId = Thread.currentThread().getId();
        LOG.debug(String.format(
                " SelfThrottlingIntercept:: SendingRequest:   threadId=%d, requestType=%s, isFirstRequest=%b, sleepDuration=%d",
                threadId, operationIsRead ? "read " : "write", isFirstRequest, sleepDuration));
    }
}

From source file:org.apache.hadoop.fs.azure.SendRequestIntercept.java

/**
 * Handler which processes the sending request event from Azure SDK. The
 * handler simply sets reset the conditional header to make all read requests
 * unconditional if reads with concurrent OOB writes are allowed.
 * /*from  w  w  w  .ja v  a 2  s  . c  o m*/
 * @param sendEvent
 *          - send event context from Windows Azure SDK.
 */
@Override
public void eventOccurred(SendingRequestEvent sendEvent) {

    if (!(sendEvent.getConnectionObject() instanceof HttpURLConnection)) {
        // Pass if there is no HTTP connection associated with this send
        // request.
        return;
    }

    // Capture the HTTP URL connection object and get size of the payload for
    // the request.
    HttpURLConnection urlConnection = (HttpURLConnection) sendEvent.getConnectionObject();

    // Determine whether this is a download request by checking that the request
    // method
    // is a "GET" operation.
    if (urlConnection.getRequestMethod().equalsIgnoreCase("GET") && isOutOfBandIoAllowed()) {
        // If concurrent reads on OOB writes are allowed, reset the if-match
        // condition on the conditional header.
        urlConnection.setRequestProperty(HeaderConstants.IF_MATCH, ALLOW_ALL_REQUEST_PRECONDITIONS);

        // In the Java AzureSDK the packet is signed before firing the
        // SendRequest. Setting
        // the conditional packet header property changes the contents of the
        // packet, therefore the packet has to be re-signed.
        try {
            // Sign the request. GET's have no payload so the content length is
            // zero.
            StorageCredentialsHelper.signBlobAndQueueRequest(getCredentials(), urlConnection, -1L,
                    getOperationContext());
        } catch (InvalidKeyException e) {
            // Log invalid key exception to track signing error before the send
            // fails.
            String errString = String.format(
                    "Received invalid key exception when attempting sign packet." + " Cause: %s",
                    e.getCause().toString());
            LOG.error(errString);
        } catch (StorageException e) {
            // Log storage exception to track signing error before the call fails.
            String errString = String.format(
                    "Received storage exception when attempting to sign packet." + " Cause: %s",
                    e.getCause().toString());
            LOG.error(errString);
        }
    }
}

From source file:it.geosolutions.httpproxy.HttpProxyTest.java

@Test
public void testDoGet() throws Exception {

    // ////////////////////////////
    // Test with a correct request
    // ////////////////////////////

    URL url = new URL("http://localhost:8080/http_proxy/proxy/?"
            + "url=http%3A%2F%2Fdemo1.geo-solutions.it%2Fgeoserver%2Fwms%3F"
            + "SERVICE%3DWMS%26REQUEST%3DGetCapabilities%26version=1.1.1");

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

    String response = IOUtils.toString(con.getInputStream());

    assertNotNull(response);//from   w  w  w  .ja  v a2 s. c om
    assertTrue(
            response.indexOf("<!DOCTYPE WMT_MS_Capabilities SYSTEM \"http://demo1.geo-solutions.it:80/geoserver"
                    + "/schemas/wms/1.1.1/WMS_MS_Capabilities.dtd\">") != -1);
    assertTrue(con.getRequestMethod().equals("GET"));
    assertTrue(con.getResponseCode() == 200);

    con.disconnect();

    // ////////////////////////////
    // Test with a fake hostname
    // ////////////////////////////

    url = new URL(
            "http://localhost:8080/http_proxy/proxy/?" + "url=http%3A%2F%2FfakeServer%2Fgeoserver%2Fwms%3F"
                    + "SERVICE%3DWMS%26REQUEST%3DGetCapabilities%26version=1.1.1");

    con = (HttpURLConnection) url.openConnection();

    String message = con.getResponseMessage();

    assertNotNull(message);
    assertEquals(message, "Host Name fakeServer is not among the ones allowed for this proxy");

    assertTrue(con.getRequestMethod().equals("GET"));
    assertTrue(con.getResponseCode() == 403);

    con.disconnect();

    // ///////////////////////////////
    // Test with a fake request type
    // ///////////////////////////////

    url = new URL("http://localhost:8080/http_proxy/proxy/?"
            + "url=http%3A%2F%2Fdemo1.geo-solutions.it%2Fgeoserver%2Fwms%3F"
            + "SERVICE%3DWMS%26REQUEST%3DGetCap%26version=1.1.1");

    con = (HttpURLConnection) url.openConnection();

    message = con.getResponseMessage();

    assertNotNull(message);
    assertEquals(message, "Request Type is not among the ones allowed for this proxy");

    assertTrue(con.getRequestMethod().equals("GET"));
    assertTrue(con.getResponseCode() == 403);

    con.disconnect();
}