Example usage for java.net HttpURLConnection getHeaderFields

List of usage examples for java.net HttpURLConnection getHeaderFields

Introduction

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

Prototype

public Map<String, List<String>> getHeaderFields() 

Source Link

Document

Returns an unmodifiable Map of the header fields.

Usage

From source file:com.markuspage.jbinrepoproxy.standalone.transport.sun.URLConnectionTransportClientImpl.java

@Override
public TransportFetch httpGetTheFile() {
    TransportFetch result;//from ww  w.  j a  va2  s.c o  m
    try {
        final URL url = new URL(serverURL + theFileURI);

        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setAllowUserInteraction(false);
        final int responseCode = conn.getResponseCode();
        final String responseMessage = conn.getResponseMessage();
        InputStream responseIn = conn.getErrorStream();
        if (responseIn == null) {
            responseIn = conn.getInputStream();
        }

        // Read the body to the output if OK otherwise to the error message
        final byte[] body = IOUtils.toByteArray(responseIn);

        this.targetResponse = new TargetResponse(responseCode, conn.getHeaderFields(), body);

        result = new TransportFetch(responseCode, responseMessage, body);
    } catch (MalformedURLException ex) {
        LOG.error("Malformed URL", ex);
        result = new TransportFetch(500, ex.getLocalizedMessage(), null);
    } catch (IOException ex) {
        LOG.error("IO error", ex);
        result = new TransportFetch(500, ex.getLocalizedMessage(), null);
    }

    return result;
}

From source file:org.xframium.integrations.alm.ALMRESTConnection.java

private ALMResponse retrieveHtmlResponse(HttpURLConnection con) throws Exception {

    ALMResponse ret = new ALMResponse();

    ret.setStatusCode(con.getResponseCode());
    ret.setResponseHeaders(con.getHeaderFields());

    InputStream inputStream;// ww  w. j ava 2 s .  co m

    try {
        inputStream = con.getInputStream();
    }

    catch (Exception e) {
        inputStream = con.getErrorStream();
        ret.setFailure(e);
    }

    ByteArrayOutputStream container = new ByteArrayOutputStream();

    byte[] buf = new byte[1024];
    int read;
    while ((read = inputStream.read(buf, 0, 1024)) > 0) {
        container.write(buf, 0, read);
    }

    ret.setResponseData(container.toByteArray());

    return ret;
}

From source file:org.apache.qpid.systest.rest.SaslRestTest.java

public void testPlainSaslAuthenticationForValidCredentials() throws Exception {
    startBrokerNow();/*  w  w  w. ja v  a2 s . co m*/

    byte[] responseBytes = generatePlainClientResponse("admin", "admin");
    String responseData = Base64.encodeBase64String(responseBytes);
    String parameters = "mechanism=PLAIN&response=" + responseData;

    HttpURLConnection connection = getRestTestHelper().openManagementConnection("/rest/sasl", "POST");
    OutputStream os = connection.getOutputStream();
    os.write(parameters.getBytes());
    os.flush();

    int code = connection.getResponseCode();
    assertEquals("Unexpected response code", 200, code);

    List<String> cookies = connection.getHeaderFields().get("Set-Cookie");

    // request authenticated user details
    connection = getRestTestHelper().openManagementConnection("/rest/sasl", "GET");
    applyCookiesToConnection(cookies, connection);
    Map<String, Object> response2 = getRestTestHelper().readJsonResponseAsMap(connection);
    assertEquals("Unexpected user", "admin", response2.get("user"));
}

From source file:org.apache.qpid.systest.rest.SaslRestTest.java

public void testPlainSaslAuthenticationForIncorrectPassword() throws Exception {
    startBrokerNow();//from w  w w  .j  a  v  a2s.  co m

    byte[] responseBytes = generatePlainClientResponse("admin", "incorrect");
    String responseData = Base64.encodeBase64String(responseBytes);
    String parameters = "mechanism=PLAIN&response=" + responseData;

    HttpURLConnection connection = getRestTestHelper().openManagementConnection("/rest/sasl", "POST");
    OutputStream os = connection.getOutputStream();
    os.write(parameters.getBytes());
    os.flush();

    int code = connection.getResponseCode();
    assertEquals("Unexpected response code", 403, code);

    List<String> cookies = connection.getHeaderFields().get("Set-Cookie");

    // request authenticated user details
    connection = getRestTestHelper().openManagementConnection("/rest/sasl", "GET");
    applyCookiesToConnection(cookies, connection);
    Map<String, Object> response2 = getRestTestHelper().readJsonResponseAsMap(connection);
    assertNull("Unexpected user", response2.get("user"));
}

From source file:org.apache.qpid.systest.rest.SaslRestTest.java

public void testPlainSaslAuthenticationForNonExistingUser() throws Exception {
    startBrokerNow();/*  ww w.j ava2s.c  om*/

    byte[] responseBytes = generatePlainClientResponse("nonexisting", "admin");
    String responseData = Base64.encodeBase64String(responseBytes);
    String parameters = "mechanism=PLAIN&response=" + responseData;

    HttpURLConnection connection = getRestTestHelper().openManagementConnection("/rest/sasl", "POST");
    OutputStream os = connection.getOutputStream();
    os.write(parameters.getBytes());
    os.flush();

    int code = connection.getResponseCode();
    assertEquals("Unexpected response code", 403, code);

    List<String> cookies = connection.getHeaderFields().get("Set-Cookie");

    // request authenticated user details
    connection = getRestTestHelper().openManagementConnection("/rest/sasl", "GET");
    applyCookiesToConnection(cookies, connection);
    Map<String, Object> response2 = getRestTestHelper().readJsonResponseAsMap(connection);
    assertNull("Unexpected user", response2.get("user"));
}

From source file:com.eTilbudsavis.etasdk.network.impl.HttpURLNetwork.java

public HttpResponse performNetworking(Request<?> request) throws ClientProtocolException, IOException {

    URL url = new URL(Utils.requestToUrlAndQueryString(request));
    HttpURLConnection connection = openConnection(url, request);
    setHeaders(request, connection);//www . j  a v a  2 s . c o m
    setRequestMethod(connection, request);

    int sc = connection.getResponseCode();
    if (sc == -1) {
        throw new IOException("Connection returned invalid response code.");
    }

    ProtocolVersion pv = new ProtocolVersion("HTTP", 1, 1);
    String rm = connection.getResponseMessage();
    BasicHttpResponse response = new BasicHttpResponse(pv, sc, rm);

    HttpEntity entity = getEntity(connection);
    response.setEntity(entity);

    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }

    return response;
}

From source file:com.chaosinmotion.securechat.network.SCNetwork.java

private synchronized void sendRequest(final Request request) {
    callQueue.add(request);/*from  ww  w .j a  v  a  2s.  c  o  m*/

    // If not in background, spin the spinner
    if (request.caller instanceof WaitSpinner) {
        ((WaitSpinner) request.caller).startWaitSpinner();
        request.waitFlag = true;
    }

    request.taskFuture = ThreadPool.get().enqueueAsync(new Runnable() {
        @Override
        public void run() {
            try {
                HttpURLConnection conn = requestWith(request);

                conn.connect();
                Map<String, List<String>> headers = conn.getHeaderFields();
                List<String> clist = headers.get("Set-Cookie");
                if (clist != null) {
                    for (String cookie : clist) {
                        cookies.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
                    }
                }

                InputStream is = conn.getInputStream();
                JSONObject d = parseResult(is);
                conn.disconnect();

                final Response response = new Response();
                response.serverCode = conn.getResponseCode();
                if (d != null) {
                    response.success = d.optBoolean("success");
                    response.error = d.optInt("error");
                    response.errorMessage = d.optString("message");
                    response.exceptionStack = d.optJSONArray("exception");
                    response.data = d.optJSONObject("data");
                }

                ThreadPool.get().enqueueMain(new Runnable() {
                    @Override
                    public void run() {
                        if (request.waitFlag && ((request.caller instanceof WaitSpinner))) {
                            ((WaitSpinner) request.caller).stopWaitSpinner();
                            request.waitFlag = false;
                        }
                        callQueue.remove(request);
                        handleResponse(response, request);
                    }
                });
            } catch (Exception ex) {
                /*
                 *  This happens if there is a connection error.
                 */
                ThreadPool.get().enqueueMain(new Runnable() {
                    @Override
                    public void run() {
                        if (request.waitFlag && ((request.caller instanceof WaitSpinner))) {
                            ((WaitSpinner) request.caller).stopWaitSpinner();
                            request.waitFlag = false;
                        }
                        callQueue.remove(request);
                        handleIOError(request);
                    }
                });
            }
        }
    });
}

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

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

            // This map's null key will contain the response code and message
            for (Map.Entry<String, List<String>> header : conn.getHeaderFields().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.inaetics.pubsub.demo.config.EtcdWrapper.java

/**
 * Delete a node in etcd//from   w  ww. j a v a2  s . co  m
 * 
 * @param key
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
public JsonNode delete(String key) throws MalformedURLException, IOException {
    HttpURLConnection connection = (HttpURLConnection) new URL(url + key).openConnection();
    connection.setRequestMethod("DELETE");
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);

    InputStream response = connection.getInputStream();
    JsonNode result = new ObjectMapper().readTree(response);
    response.close();
    AddEtcdIndex(result, Long.parseLong(connection.getHeaderFields().get("X-Etcd-Index").get(0)));
    return result;
}