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:common.net.volley.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();

    stethoManager = new StethoURLConnectionManager(url);

    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());/*from w  w  w  . j a v a 2s .c  o m*/
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    requestDecompression(connection);

    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }

    setConnectionParametersForRequest(connection, request);

    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());

    stethoManager.postConnect();

    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    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.yaozu.object.volley.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());//from  w w w .  ja va2 s. c o  m
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could
        // not be retrieved.
        // Signal to the caller that something was wrong with the
        // connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
        response.setEntity(entityFromConnection(connection));
    }
    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.selene.volley.stack.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    //      if (!TextUtils.isEmpty(mUserAgent)) {
    //         map.put(HTTP.USER_AGENT, mUserAgent);
    //      }//  w  ww.j a va 2 s .c  om
    map.putAll(request.getHeaders());
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could
        // not be retrieved.
        // Signal to the caller that something was wrong with the
        // connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
        response.setEntity(entityFromConnection(connection));
    }

    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.handsome.frame.android.volley.stack.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request) throws IOException, AuthFailureError {
    HashMap<String, String> map = new HashMap<String, String>();
    if (!TextUtils.isEmpty(mUserAgent)) {
        map.put(HTTP.USER_AGENT, mUserAgent);
    }//from  ww w  . j  a v  a2s  .  com
    map.putAll(request.getHeaders());

    URL parsedUrl = new URL(request.getUrl());
    HttpURLConnection connection = openConnection(parsedUrl, request);

    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    if (HandsomeApplication.getCookies() != null) {
        HDLog.d(TAG + "-Req-Cookie:", HandsomeApplication.getCookies().toString());
        connection.addRequestProperty("Cookie", HandsomeApplication.getCookies());
    } else {
        HDLog.d(TAG + "-Req-Cookie:", "null");
    }
    setConnectionParametersForRequest(connection, request);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }

    StatusLine responseStatus = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1),
            connection.getResponseCode(), connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            if (header.getKey().equalsIgnoreCase("Set-Cookie")) {
                List<String> cookies = header.getValue();
                HashMap<String, HttpCookie> cookieMap = new HashMap<String, HttpCookie>();
                for (String string : cookies) {
                    List<HttpCookie> cookie = HttpCookie.parse(string);
                    for (HttpCookie httpCookie : cookie) {
                        cookieMap.put(httpCookie.getName(), httpCookie);
                    }
                }
                HandsomeApplication.setCookies(cookieMap);
                HDLog.d(TAG + "-Rsp-Cookie:", HandsomeApplication.getCookies().toString());
            } else {
                Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
                response.addHeader(h);
            }
        }
    }

    return response;
}

From source file:ai.eve.volley.stack.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request) throws IOException, AuthFailureError {
    HashMap<String, String> map = new HashMap<String, String>();
    if (!TextUtils.isEmpty(mUserAgent)) {
        map.put(HTTP.USER_AGENT, mUserAgent);
    }/*from ww  w  .  ja v  a 2s. c o m*/
    if (!TextUtils.isEmpty(mSignInfo)) {
        map.put("SIGN", ESecurity.Encrypt(mSignInfo));
    }
    map.putAll(request.getHeaders());

    URL parsedUrl = new URL(request.getUrl());
    HttpURLConnection connection = openConnection(parsedUrl, request);

    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    if (EApplication.getCookies() != null) {
        ELog.I("cookie", EApplication.getCookies().toString());
        connection.addRequestProperty("Cookie", EApplication.getReqCookies());
    } else {
        ELog.I("cookie", "null");
    }
    setConnectionParametersForRequest(connection, request);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }

    StatusLine responseStatus = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1),
            connection.getResponseCode(), connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            if (header.getKey().equalsIgnoreCase("Set-Cookie")) {
                List<String> cookies = header.getValue();
                HashMap<String, HttpCookie> cookieMap = new HashMap<String, HttpCookie>();
                for (String string : cookies) {
                    List<HttpCookie> cookie = HttpCookie.parse(string);
                    for (HttpCookie httpCookie : cookie) {
                        if (httpCookie.getDomain() != null && httpCookie.getPath() != null) {
                            cookieMap.put(httpCookie.getName() + httpCookie.getDomain() + httpCookie.getPath(),
                                    httpCookie);
                        } else if (httpCookie.getDomain() == null && httpCookie.getPath() != null) {
                            cookieMap.put(httpCookie.getName() + httpCookie.getPath(), httpCookie);
                        } else if (httpCookie.getDomain() != null && httpCookie.getPath() == null) {
                            cookieMap.put(httpCookie.getName() + httpCookie.getDomain(), httpCookie);
                        } else {
                            cookieMap.put(httpCookie.getName(), httpCookie);
                        }
                    }
                }

                EApplication.setCookies(cookieMap);
                if (EApplication.getCookies() != null) {
                    ELog.I("?cookie", EApplication.getCookies().toString());
                }
            } else {
                Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
                response.addHeader(h);
            }
        }
    }

    return response;
}

From source file:TimestreamsTests.java

/**
 * Performs HTTP post for a given URL//from  w  ww  . j a  v  a2s.  c  om
 * 
 * @param url
 *            is the URL to get
 * @param params
 *            is a URL encoded string in the form x=y&a=b...
 * @return a String with the contents of the get
 */
private Map<String, List<String>> doPut(URL url, String params) {
    HttpURLConnection connection;
    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length));

        connection.setDoInput(true);
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(params);
        out.close();
        Map<String, List<String>> responseHeaderFields = connection.getHeaderFields();
        System.out.println(responseHeaderFields);
        if (responseHeaderFields.get(null).get(0).equals("HTTP/1.1 200 OK")) {
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            System.out.println(response);
        }
        return responseHeaderFields;
    } catch (IOException e1) {
        fail("Post " + url + " failed: " + e1.getLocalizedMessage());
    }

    return null;
}

From source file:com.twotoasters.android.hoot.HootTransportHttpUrlConnection.java

@Override
public HootResult synchronousExecute(HootRequest request) {
    if (request.isCancelled()) {
        return request.getResult();
    }// ww  w  .  jav a 2 s .c o m

    mStreamingMode = (request.getQueryParameters() == null && request.getData() == null
            && request.getMultipartEntity() == null) ? StreamingMode.CHUNKED : StreamingMode.FIXED;

    if (request.getStreamingMode() == HootRequest.STREAMING_MODE_FIXED) {
        mStreamingMode = StreamingMode.FIXED;
    }

    HttpURLConnection connection = null;
    try {
        String url = request.buildUri().toString();
        Log.v(TAG, "Executing [" + url + "]");
        connection = (HttpURLConnection) new URL(url).openConnection();
        if (connection instanceof HttpsURLConnection) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setHostnameVerifier(mSSLHostNameVerifier);
        }
        connection.setConnectTimeout(mTimeout);
        connection.setReadTimeout(mTimeout);
        synchronized (mConnectionMap) {
            mConnectionMap.put(request, connection);
        }

        setRequestMethod(request, connection);
        setRequestHeaders(request, connection);

        if (request.getMultipartEntity() != null) {
            setMultipartEntity(request, connection);
        } else if (request.getData() != null) {
            setRequestData(request, connection);
        }

        HootResult hootResult = request.getResult();
        hootResult.setResponseCode(connection.getResponseCode());
        Log.d(TAG, " - received response code [" + connection.getResponseCode() + "]");
        if (request.getResult().isSuccess()) {
            hootResult.setHeaders(connection.getHeaderFields());
            hootResult.setResponseStream(new BufferedInputStream(connection.getInputStream()));
        } else {
            hootResult.setResponseStream(new BufferedInputStream(connection.getErrorStream()));
        }
        request.deserializeResult();
    } catch (Exception e) {
        request.getResult().setException(e);
        e.printStackTrace();
    } finally {
        if (connection != null) {
            synchronized (mConnectionMap) {
                mConnectionMap.remove(request);
            }
            connection.disconnect();
            connection = null;
        }
    }
    return request.getResult();
}

From source file:io.warp10.script.functions.URLFETCH.java

@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {

    if (!stack.isAuthenticated()) {
        throw new WarpScriptException(getName() + " requires the stack to be authenticated.");
    }/*from w  ww.  jav a 2 s .  co  m*/

    Object o = stack.pop();

    if (!(o instanceof String) && !(o instanceof List)) {
        throw new WarpScriptException(getName() + " expects a URL or list thereof on top of the stack.");
    }

    List<URL> urls = new ArrayList<URL>();

    try {
        if (o instanceof String) {
            urls.add(new URL(o.toString()));
        } else {
            for (Object oo : (List) o) {
                urls.add(new URL(oo.toString()));
            }
        }
    } catch (MalformedURLException mue) {
        throw new WarpScriptException(getName() + " encountered an invalid URL.");
    }

    //
    // Check URLs
    //

    for (URL url : urls) {
        if (!StandaloneWebCallService.checkURL(url)) {
            throw new WarpScriptException(getName() + " encountered an invalid URL '" + url + "'");
        }
    }

    //
    // Check that we do not exceed the maxurlfetch limit
    //

    AtomicLong urlfetchCount = (AtomicLong) stack.getAttribute(WarpScriptStack.ATTRIBUTE_URLFETCH_COUNT);
    AtomicLong urlfetchSize = (AtomicLong) stack.getAttribute(WarpScriptStack.ATTRIBUTE_URLFETCH_SIZE);

    if (urlfetchCount.get()
            + urls.size() > (long) stack.getAttribute(WarpScriptStack.ATTRIBUTE_URLFETCH_LIMIT)) {
        throw new WarpScriptException(getName() + " is limited to "
                + stack.getAttribute(WarpScriptStack.ATTRIBUTE_URLFETCH_LIMIT) + " calls.");
    }

    List<Object> results = new ArrayList<Object>();

    for (URL url : urls) {
        urlfetchCount.addAndGet(1);

        HttpURLConnection conn = null;

        try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(false);
            conn.setRequestMethod("GET");

            byte[] buf = new byte[8192];

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            InputStream in = conn.getInputStream();

            while (true) {
                int len = in.read(buf);

                if (len < 0) {
                    break;
                }

                if (urlfetchSize.get() + baos.size()
                        + len > (long) stack.getAttribute(WarpScriptStack.ATTRIBUTE_URLFETCH_MAXSIZE)) {
                    throw new WarpScriptException(getName()
                            + " would exceed maximum size of content which can be retrieved via URLFETCH ("
                            + stack.getAttribute(WarpScriptStack.ATTRIBUTE_URLFETCH_MAXSIZE) + " bytes)");
                }

                baos.write(buf, 0, len);
            }

            urlfetchSize.addAndGet(baos.size());

            List<Object> res = new ArrayList<Object>();

            res.add(conn.getResponseCode());
            Map<String, List<String>> hdrs = conn.getHeaderFields();

            if (hdrs.containsKey(null)) {
                List<String> statusMsg = hdrs.get(null);
                if (statusMsg.size() > 0) {
                    res.add(statusMsg.get(0));
                } else {
                    res.add("");
                }
            } else {
                res.add("");
            }
            hdrs.remove(null);
            res.add(hdrs);
            res.add(Base64.encodeBase64String(baos.toByteArray()));

            results.add(res);
        } catch (IOException ioe) {
            throw new WarpScriptException(getName() + " encountered an error while fetching '" + url + "'");
        } finally {
            if (null != conn) {
                conn.disconnect();
            }
        }
    }

    stack.push(results);

    return stack;
}

From source file:TimestreamsTests.java

/**
 * Performs HTTP post for a given URL//w ww .j  ava  2 s . c o  m
 * 
 * @param url
 *            is the URL to get
 * @param params
 *            is a URL encoded string in the form x=y&a=b...
 * @return a String with the contents of the get
 */
private Map<String, List<String>> doPost(URL url, String params) {
    HttpURLConnection connection;
    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length));

        connection.setDoInput(true);
        connection.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(params);
        wr.flush();
        wr.close();
        Map<String, List<String>> responseHeaderFields = connection.getHeaderFields();
        System.out.println(responseHeaderFields);
        if (responseHeaderFields.get(null).get(0).equals("HTTP/1.1 200 OK")) {
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            System.out.println(response);
        }
        return responseHeaderFields;
    } catch (IOException e1) {
        fail("Post " + url + " failed: " + e1.getLocalizedMessage());
    }

    return null;
}

From source file:org.deviceconnect.android.deviceplugin.irkit.IRKitManager.java

/**
 * ??IP???IRKit???./*  w  ww. j  a v  a  2  s.  c om*/
 * 
 * @param ip IP
 * @param callback ?
 */
public void checkIfTargetIsIRKit(final String ip, final CheckingIRKitCallback callback) {
    new Thread(new Runnable() {

        @Override
        public void run() {

            boolean isIRKit = false;
            HttpURLConnection req = null;
            try {
                req = createGetRequest(ip, "/messages");
                executeRequest(req);
                Map<String, List<String>> headers = req.getHeaderFields();
                for (String h : headers.keySet()) {
                    if (h == null) {
                        continue;
                    }
                    if (h.equals("Server")) {
                        for (String v : headers.get(h)) {
                            if (v.contains(TAG)) {
                                isIRKit = true;
                                break;
                            }
                        }
                        if (isIRKit) {
                            break;
                        }
                    }
                }
            } catch (IOException e) {
                if (BuildConfig.DEBUG) {
                    Log.e(TAG, "disconnect:" + isIRKit, e);

                }
            } finally {
                if (req != null) {
                    req.disconnect();
                }
            }

            callback.onChecked(isIRKit);
        }
    }).start();
}