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:org.apache.hadoop.fs.azure.metrics.ResponseReceivedMetricUpdater.java

/**
 * Handle the response-received event from Azure SDK.
 *//*from w  ww. j a  v  a2s.  co m*/
@Override
public void eventOccurred(ResponseReceivedEvent eventArg) {
    instrumentation.webResponse();
    if (!(eventArg.getConnectionObject() instanceof HttpURLConnection)) {
        // Typically this shouldn't happen, but just let it pass
        return;
    }
    HttpURLConnection connection = (HttpURLConnection) eventArg.getConnectionObject();
    RequestResult currentResult = eventArg.getRequestResult();
    if (currentResult == null) {
        // Again, typically shouldn't happen, but let it pass
        return;
    }

    long requestLatency = currentResult.getStopDate().getTime() - currentResult.getStartDate().getTime();

    if (currentResult.getStatusCode() == HttpURLConnection.HTTP_CREATED
            && connection.getRequestMethod().equalsIgnoreCase("PUT")) {
        // If it's a PUT with an HTTP_CREATED status then it's a successful
        // block upload.
        long length = getRequestContentLength(connection);
        if (length > 0) {
            blockUploadGaugeUpdater.blockUploaded(currentResult.getStartDate(), currentResult.getStopDate(),
                    length);
            instrumentation.rawBytesUploaded(length);
            instrumentation.blockUploaded(requestLatency);
        }
    } else if (currentResult.getStatusCode() == HttpURLConnection.HTTP_PARTIAL
            && connection.getRequestMethod().equalsIgnoreCase("GET")) {
        // If it's a GET with an HTTP_PARTIAL status then it's a successful
        // block download.
        long length = getResponseContentLength(connection);
        if (length > 0) {
            blockUploadGaugeUpdater.blockDownloaded(currentResult.getStartDate(), currentResult.getStopDate(),
                    length);
            instrumentation.rawBytesDownloaded(length);
            instrumentation.blockDownloaded(requestLatency);
        }
    }
}

From source file:org.apache.jmeter.protocol.http.control.CacheManager.java

/**
 * Check the cache, and if there is a match, set the headers:
 * <ul>/*w w  w.  j a  va 2s. c  om*/
 * <li>If-Modified-Since</li>
 * <li>If-None-Match</li>
 * </ul>
 * @param url {@link URL} to look up in cache
 * @param conn where to set the headers
 */
public void setHeaders(HttpURLConnection conn, URL url) {
    CacheEntry entry = getCache().get(url.toString());
    if (log.isDebugEnabled()) {
        log.debug(conn.getRequestMethod() + "(Java) " + url.toString() + " " + entry);
    }
    if (entry != null) {
        final String lastModified = entry.getLastModified();
        if (lastModified != null) {
            conn.addRequestProperty(HTTPConstants.IF_MODIFIED_SINCE, lastModified);
        }
        final String etag = entry.getEtag();
        if (etag != null) {
            conn.addRequestProperty(HTTPConstants.IF_NONE_MATCH, etag);
        }
    }
}

From source file:com.apache.ivy.BasicURLHandler.java

private boolean checkStatusCode(URL url, HttpURLConnection con) throws IOException {
    int status = con.getResponseCode();
    if (status == HttpStatus.SC_OK) {
        return true;
    }/*  w w  w  . java 2  s. c o  m*/

    // IVY-1328: some servers return a 204 on a HEAD request
    if ("HEAD".equals(con.getRequestMethod()) && (status == 204)) {
        return true;
    }

    //Message.debug("HTTP response status: " + status + " url=" + url);
    if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
        //Message.warn("Your proxy requires authentication.");
    } else if (String.valueOf(status).startsWith("4")) {
        //Message.verbose("CLIENT ERROR: " + con.getResponseMessage() + " url=" + url);
    } else if (String.valueOf(status).startsWith("5")) {
        //Message.error("SERVER ERROR: " + con.getResponseMessage() + " url=" + url);
    }
    return false;
}

From source file:pt.lsts.neptus.comm.iridium.HubIridiumMessenger.java

@Override
public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception {

    NeptusLog.pub().info("Polling messages since " + dateToString(timeSince));

    String since = null;/*from   w  w  w. ja v  a 2s.com*/
    if (timeSince != null)
        since = dateToString(timeSince);
    URL u = new URL(messagesUrl + "?since=" + since);
    if (since == null)
        u = new URL(messagesUrl);
    HttpURLConnection conn = (HttpURLConnection) u.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("GET");
    conn.setConnectTimeout(timeoutMillis);
    Gson gson = new Gson();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOUtils.copy(conn.getInputStream(), baos);

    logHubInteraction("Iridium Poll", u.toString(), conn.getRequestMethod(), "" + conn.getResponseCode(), "",
            new String(baos.toByteArray()));

    if (conn.getResponseCode() != 200)
        throw new Exception(
                "Hub iridium server returned " + conn.getResponseCode() + ": " + conn.getResponseMessage());
    HubMessage[] msgs = gson.fromJson(baos.toString(), HubMessage[].class);

    Vector<IridiumMessage> ret = new Vector<>();

    for (HubMessage m : msgs) {
        ret.add(m.message());
    }

    return ret;
}

From source file:com.microsoft.azure.storage.core.Utility.java

/**
 * Logs the HttpURLConnection request. If an exception is encountered, logs nothing.
 * /* w  w w.  j a  v  a 2s  .  co m*/
 * @param conn
 *            The HttpURLConnection to serialize.
 * @param opContext 
 *            The operation context which provides the logger.
 */
public static void logHttpRequest(HttpURLConnection conn, OperationContext opContext) throws IOException {
    if (Logger.shouldLog(opContext)) {
        try {
            StringBuilder bld = new StringBuilder();

            bld.append(conn.getRequestMethod());
            bld.append(" ");
            bld.append(conn.getURL());
            bld.append("\n");

            // The Authorization header will not appear due to a security feature in HttpURLConnection
            for (Map.Entry<String, List<String>> header : conn.getRequestProperties().entrySet()) {
                if (header.getKey() != null) {
                    bld.append(header.getKey());
                    bld.append(": ");
                }

                for (int i = 0; i < header.getValue().size(); i++) {
                    bld.append(header.getValue().get(i));
                    if (i < header.getValue().size() - 1) {
                        bld.append(",");
                    }
                }
                bld.append('\n');
            }

            Logger.trace(opContext, bld.toString());
        } catch (Exception e) {
            // Do nothing
        }
    }
}

From source file:org.jboss.aerogear.android.impl.http.HttpRestProviderTest.java

private void testDelete(int statusCode) throws Exception {
    HttpURLConnection connection = mock(HttpURLConnection.class);
    HttpUrlConnectionProvider providerProvider = new HttpUrlConnectionProvider(connection);
    final String id = "1";

    when(connection.getResponseCode()).thenReturn(statusCode);
    when(connection.getInputStream()).thenReturn(new ByteArrayInputStream(EMPTY_DATA));
    when(connection.getErrorStream()).thenReturn(new ByteArrayInputStream(EMPTY_DATA));
    when(connection.getHeaderFields()).thenReturn(RESPONSE_HEADERS);
    doCallRealMethod().when(connection).setRequestMethod(anyString());
    when(connection.getRequestMethod()).thenCallRealMethod();

    HttpRestProvider provider = new HttpRestProvider(SIMPLE_URL);
    setPrivateField(provider, "connectionPreparer", providerProvider);

    HeaderAndBody result = provider.delete(id);

    assertArrayEquals(EMPTY_DATA, result.getBody());
    assertEquals("DELETE", connection.getRequestMethod());
    assertNotNull(result.getHeader(HEADER_KEY1_NAME));
    assertNotNull(result.getHeader(HEADER_KEY2_NAME));
    assertEquals(HEADER_VALUE, result.getHeader(HEADER_KEY2_NAME));
    assertEquals(id, providerProvider.id);
}

From source file:org.jboss.aerogear.android.impl.http.HttpRestProviderTest.java

@Test
public void testPost() throws Exception {

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(RESPONSE_DATA.length);
    HttpURLConnection connection = mock(HttpURLConnection.class);
    HttpRestProvider provider = new HttpRestProvider(SIMPLE_URL);
    setPrivateField(provider, "connectionPreparer", new HttpUrlConnectionProvider(connection));

    doReturn(HttpStatus.SC_OK).when(connection).getResponseCode();
    when(connection.getInputStream()).thenReturn(new ByteArrayInputStream(RESPONSE_DATA));
    when(connection.getOutputStream()).thenReturn(outputStream);
    when(connection.getHeaderFields()).thenReturn(RESPONSE_HEADERS);
    doCallRealMethod().when(connection).setRequestMethod(anyString());
    when(connection.getRequestMethod()).thenCallRealMethod();

    HeaderAndBody result = provider.post(REQUEST_DATA);
    assertEquals("POST", connection.getRequestMethod());
    assertArrayEquals(RESPONSE_DATA, result.getBody());
    assertNotNull(result.getHeader(HEADER_KEY1_NAME));
    assertNotNull(result.getHeader(HEADER_KEY2_NAME));
    assertEquals(HEADER_VALUE, result.getHeader(HEADER_KEY2_NAME));
    assertArrayEquals(RESPONSE_DATA, outputStream.toByteArray());

}

From source file:com.idean.atthack.network.RequestHelper.java

private Result sendHttpGet(String urlStr) {
    HttpURLConnection conn = null;
    try {/*from w  w  w  .j  a v  a  2 s  . c o m*/
        URL url = new URL(urlStr);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(HttpVerb.GET.name());
        setBasicAuth(conn);
        conn.connect();
        Log.d(TAG, "[" + conn.getRequestMethod() + "] to " + url.toString());

        String body = readStream(conn.getInputStream());
        return new Result(conn.getResponseCode(), body);
    } catch (IOException e) {
        return new Result(e.getClass() + ": " + e.getMessage());
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:org.jboss.aerogear.android.impl.http.HttpRestProviderTest.java

private void testPut(int statusCode) throws Exception {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(RESPONSE_DATA.length);
    final HttpURLConnection connection = mock(HttpURLConnection.class);
    HttpUrlConnectionProvider providerProvider = new HttpUrlConnectionProvider(connection);
    final String id = "1";

    doAnswer(new ConnectingAnswer<Integer>(connection, statusCode)).when(connection).getResponseCode();
    doAnswer(new ConnectingAnswer<ByteArrayInputStream>(connection, new ByteArrayInputStream(RESPONSE_DATA)))
            .when(connection).getInputStream();
    doAnswer(new ConnectingAnswer<ByteArrayOutputStream>(connection, outputStream)).when(connection)
            .getOutputStream();// www.  j  ava2 s. c  o  m
    doAnswer(new ConnectingAnswer<Map>(connection, RESPONSE_HEADERS)).when(connection).getHeaderFields();
    doCallRealMethod().when(connection).setRequestMethod(anyString());
    when(connection.getRequestMethod()).thenCallRealMethod();

    HttpRestProvider provider = new HttpRestProvider(SIMPLE_URL);
    setPrivateField(provider, "connectionPreparer", providerProvider);

    HeaderAndBody result = provider.put(id, REQUEST_DATA);
    assertEquals("PUT", connection.getRequestMethod());
    assertArrayEquals(RESPONSE_DATA, result.getBody());
    assertNotNull(result.getHeader(HEADER_KEY1_NAME));
    assertNotNull(result.getHeader(HEADER_KEY2_NAME));
    assertEquals(HEADER_VALUE, result.getHeader(HEADER_KEY2_NAME));
    assertArrayEquals(RESPONSE_DATA, outputStream.toByteArray());
    assertEquals(id, providerProvider.id);
}

From source file:com.idean.atthack.network.RequestHelper.java

/**
 * Send secured HTTP Post to argument URL. Secured with basic http
 * authentication//from w  ww.j  av a 2  s .c  o  m
 */
private Result sendHttpPost(JSONObject obj, String urlStr) {
    HttpURLConnection conn = null;
    try {
        URL url = new URL(urlStr);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(HttpVerb.POST.name());
        conn.setRequestProperty("Content-Type", "application/json");
        setBasicAuth(conn);
        conn.setDoOutput(true);
        writeBody(conn, obj);
        conn.connect();
        Log.d(TAG, "[" + conn.getRequestMethod() + "] to " + url.toString());

        String body = readStream(conn.getInputStream());
        return new Result(conn.getResponseCode(), body);
    } catch (IOException e) {
        return new Result(e.getClass() + ": " + e.getMessage());
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}