Example usage for java.net HttpURLConnection getRequestProperty

List of usage examples for java.net HttpURLConnection getRequestProperty

Introduction

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

Prototype

public String getRequestProperty(String key) 

Source Link

Document

Returns the value of the named general request property for this connection.

Usage

From source file:org.witness.ssc.xfer.utils.PublishingUtils.java

private String gdataUpload(File file, String uploadUrl, int start, int end, Activity activity)
        throws IOException {

    mActivity = activity;//from   ww  w  .j  a v a2  s.  c  o  m

    int chunk = end - start + 1;
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];
    FileInputStream fileStream = new FileInputStream(file);

    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);

    // some mobile proxies do not support PUT, using X-HTTP-Method-Override
    // to get around this problem
    if (isFirstRequest()) {
        Log.d(TAG, String.format("Uploaded %d bytes so far, using POST method.", (int) totalBytesUploaded));
        urlConnection.setRequestMethod("POST");
    } else {
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT");
        Log.d(TAG, String.format("Uploaded %d bytes so far, using POST with X-HTTP-Method-Override PUT method.",
                (int) totalBytesUploaded));
    }
    urlConnection.setDoOutput(true);
    urlConnection.setFixedLengthStreamingMode(chunk);
    // /XXX hardcoded video mimetype
    urlConnection.setRequestProperty("Content-Type", "video/mp4");
    urlConnection.setRequestProperty("Content-Range",
            String.format("bytes %d-%d/%d", start, end, file.length()));
    Log.d(TAG, urlConnection.getRequestProperty("Content-Range"));

    OutputStream outStreamWriter = urlConnection.getOutputStream();

    fileStream.skip(start);

    int bytesRead;
    int totalRead = 0;

    Thread thread = new Thread() {

        public void run() {
            int lastPercent = 0;

            while (lastPercent < 100) {
                if (lastPercent != percentUploaded) {
                    ((SSCXferActivity) mActivity).showProgress("uploading...", percentUploaded);
                    lastPercent = percentUploaded;
                }

                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }

            }
        }
    };
    thread.start();

    while ((bytesRead = fileStream.read(buffer, 0, bufferSize)) != -1) {
        outStreamWriter.write(buffer, 0, bytesRead);
        totalRead += bytesRead;
        this.totalBytesUploaded += bytesRead;

        percentUploaded = (int) (((float) totalBytesUploaded) / ((float) currentFileSize) * 99f);

        if (totalRead == (end - start + 1)) {
            break;
        }
    }

    outStreamWriter.close();

    int responseCode = urlConnection.getResponseCode();

    Log.d(TAG, "responseCode=" + responseCode);
    Log.d(TAG, "responseMessage=" + urlConnection.getResponseMessage());

    try {
        if (responseCode == 201) {
            String videoId = parseVideoId(urlConnection.getInputStream());

            Log.i(TAG, "Youtube video submitted - new video id is " + videoId);

            // 100% finished here.

            // dialog.setProgress(100);

            return videoId;
        } else if (responseCode == 200) {
            Set<String> keySet = urlConnection.getHeaderFields().keySet();
            String keys = urlConnection.getHeaderFields().keySet().toString();
            Log.d(TAG, String.format("Headers keys %s.", keys));
            for (String key : keySet) {
                Log.d(TAG, String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key)));
            }
            Log.w(TAG, "Received 200 response during resumable uploading");
            throw new IOException(String.format("Unexpected response code : responseCode=%d responseMessage=%s",
                    responseCode, urlConnection.getResponseMessage()));
        } else {
            if ((responseCode + "").startsWith("5")) {
                String error = String.format("responseCode=%d responseMessage=%s", responseCode,
                        urlConnection.getResponseMessage());
                Log.w(TAG, error);
                // TODO - this exception will trigger retry mechanism to
                // kick in
                // TODO - even though it should not, consider introducing a
                // new type so
                // TODO - resume does not kick in upon 5xx
                throw new IOException(error);
            } else if (responseCode == 308) {
                // OK, the chunk completed successfully
                Log.d(TAG, String.format("responseCode=%d responseMessage=%s", responseCode,
                        urlConnection.getResponseMessage()));
            } else {
                // TODO - this case is not handled properly yet
                Log.w(TAG, String.format("Unexpected return code : %d %s while uploading :%s", responseCode,
                        urlConnection.getResponseMessage(), uploadUrl));
            }
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java

private String gdataUpload(File file, String uploadUrl, int start, int end) throws IOException {
    int chunk = end - start + 1;
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];
    FileInputStream fileStream = new FileInputStream(file);

    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);
    // some mobile proxies do not support PUT, using X-HTTP-Method-Override
    // to get around this problem
    if (isFirstRequest()) {
        Log.d(TAG, String.format("Uploaded %d bytes so far, using POST method.", (int) totalBytesUploaded));
        urlConnection.setRequestMethod("POST");
    } else {// w  w  w .  j a  v  a  2s  .c o m
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT");
        Log.d(TAG, String.format("Uploaded %d bytes so far, using POST with X-HTTP-Method-Override PUT method.",
                (int) totalBytesUploaded));
    }
    urlConnection.setDoOutput(true);
    urlConnection.setFixedLengthStreamingMode(chunk);
    // /XXX hardcoded video mimetype
    urlConnection.setRequestProperty("Content-Type", "video/mp4");
    urlConnection.setRequestProperty("Content-Range",
            String.format("bytes %d-%d/%d", start, end, file.length()));
    Log.d(TAG, urlConnection.getRequestProperty("Content-Range"));

    OutputStream outStreamWriter = urlConnection.getOutputStream();

    fileStream.skip(start);

    int bytesRead;
    int totalRead = 0;
    while ((bytesRead = fileStream.read(buffer, 0, bufferSize)) != -1) {
        outStreamWriter.write(buffer, 0, bytesRead);
        totalRead += bytesRead;
        this.totalBytesUploaded += bytesRead;

        // double percent = (totalBytesUploaded / currentFileSize) * 99;

        /*
         * Log.d(TAG, String.format(
         * "fileSize=%f totalBytesUploaded=%f percent=%f", currentFileSize,
         * totalBytesUploaded, percent));
         */

        if (totalRead == (end - start + 1)) {
            break;
        }
    }

    outStreamWriter.close();

    int responseCode = urlConnection.getResponseCode();

    Log.d(TAG, "responseCode=" + responseCode);
    Log.d(TAG, "responseMessage=" + urlConnection.getResponseMessage());

    try {
        if (responseCode == 201) {
            String videoId = parseVideoId(urlConnection.getInputStream());

            Log.i(TAG, "Youtube video submitted - new video id is " + videoId);

            // 100% finished here.

            // dialog.setProgress(100);

            return videoId;
        } else if (responseCode == 200) {
            Set<String> keySet = urlConnection.getHeaderFields().keySet();
            String keys = urlConnection.getHeaderFields().keySet().toString();
            Log.d(TAG, String.format("Headers keys %s.", keys));
            for (String key : keySet) {
                Log.d(TAG, String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key)));
            }
            Log.w(TAG, "Received 200 response during resumable uploading");
            throw new IOException(String.format("Unexpected response code : responseCode=%d responseMessage=%s",
                    responseCode, urlConnection.getResponseMessage()));
        } else {
            if ((responseCode + "").startsWith("5")) {
                String error = String.format("responseCode=%d responseMessage=%s", responseCode,
                        urlConnection.getResponseMessage());
                Log.w(TAG, error);
                // TODO - this exception will trigger retry mechanism to
                // kick in
                // TODO - even though it should not, consider introducing a
                // new type so
                // TODO - resume does not kick in upon 5xx
                throw new IOException(error);
            } else if (responseCode == 308) {
                // OK, the chunk completed successfully
                Log.d(TAG, String.format("responseCode=%d responseMessage=%s", responseCode,
                        urlConnection.getResponseMessage()));
            } else {
                // TODO - this case is not handled properly yet
                Log.w(TAG, String.format("Unexpected return code : %d %s while uploading :%s", responseCode,
                        urlConnection.getResponseMessage(), uploadUrl));
            }
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.codehaus.wadi.web.impl.StandardHttpProxy.java

protected void doProxy(URI uri, WebInvocation context) throws ProxyingException {
    HttpServletRequest req = context.getHreq();
    HttpServletResponse res = context.getHres();

    String requestURI = getRequestURI(req);
    String qs = req.getQueryString();
    if (qs != null) {
        requestURI = new StringBuffer(requestURI).append("?").append(qs).toString();
    }//from  www.ja v a  2  s. c o m

    URL url = null;
    try {
        url = new URL("http", uri.getHost(), uri.getPort(), requestURI);
        if (_log.isTraceEnabled())
            _log.trace("proxying to: " + url);
    } catch (MalformedURLException e) {
        if (_log.isWarnEnabled())
            _log.warn("bad proxy url: " + url, e);
        throw new IrrecoverableException("bad proxy url", e);
    }

    long startTime = System.currentTimeMillis();

    HttpURLConnection huc = null;
    String m = req.getMethod();
    try {
        huc = (HttpURLConnection) url.openConnection(); // IOException
        huc.setRequestMethod(m); // ProtocolException
    } catch (ProtocolException e) {
        if (_log.isWarnEnabled())
            _log.warn("unsupported http method: " + m, e);
        throw new IrrecoverableException("unsupported HTTP method: " + m, e);
    } catch (IOException e) {
        if (_log.isWarnEnabled())
            _log.warn("proxy IO problem", e);
        throw new RecoverableException("could not open proxy connection", e);
    }

    huc.setAllowUserInteraction(false);
    huc.setInstanceFollowRedirects(false);

    // check connection header
    // TODO - this might need some more time: see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
    String connectionHdr = req.getHeader("Connection"); // TODO - what if there are multiple values ?
    if (connectionHdr != null) {
        connectionHdr = connectionHdr.toLowerCase();
        if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close"))
            connectionHdr = null; // TODO  ??
    }

    // copy headers - inefficient, but we are constrained by servlet API
    {
        for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
            String hdr = (String) e.nextElement();
            String lhdr = hdr.toLowerCase();

            if (_DontProxyHeaders.contains(lhdr))
                continue;
            if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0) // what is going on here ?
                continue;
            // HTTP/1.1 proxies MUST parse the Connection header field before a message is forwarded and, for each connection-token in this field, remove any header field(s) from the message with the same name as the connection-token. Connection options are signaled by the presence of a connection-token in the Connection header field, not by any corresponding additional header field(s), since the additional header field may not be sent if there are no parameters associated with that connection option
            if (_WADI_IsSecure.equals(hdr)) // don't worry about case - we should be the only one messing with this header...
                continue; // strip this out - we may be being spoofed

            for (Enumeration f = req.getHeaders(hdr); f.hasMoreElements();) {
                String val = (String) f.nextElement();
                if (val != null) {
                    huc.addRequestProperty(hdr, val);
                }
            }
        }
    }

    // content ?
    boolean hasContent = false;
    {
        int contentLength = 0;
        String tmp = huc.getRequestProperty("Content-Length");
        if (tmp != null) {
            try {
                contentLength = Integer.parseInt(tmp);
            } catch (NumberFormatException ignore) {
                // ignore
            }
        }

        if (contentLength > 0)
            hasContent = true;
        else
            hasContent = (huc.getRequestProperty("Content-Type") != null);
    }

    // proxy
    {
        huc.addRequestProperty("Via", "1.1 " + req.getLocalName() + ":" + req.getLocalPort() + " \"WADI\""); // TODO - should we be giving out personal details ?
        huc.addRequestProperty("X-Forwarded-For", req.getRemoteAddr()); // adds last link in request chain...
        // String tmp=uc.getRequestProperty("Max-Forwards"); // TODO - do we really need to bother with this ?
    }

    // cache-control
    {
        String cacheControl = huc.getRequestProperty("Cache-Control");
        if (cacheControl != null
                && (cacheControl.indexOf("no-cache") >= 0 || cacheControl.indexOf("no-store") >= 0))
            huc.setUseCaches(false);
    }

    // confidentiality
    {
        if (req.isSecure()) {
            huc.addRequestProperty(_WADI_IsSecure, req.getLocalAddr().toString());
        }

        // at the other end, if this header is present we must :

        // wrap the request so that req.isSecure()=true, before processing...
        // mask the header - so it is never seen by the app.

        // the code for the other end should live in this class.

        // this code should also confirm that it not being spoofed by confirming that req.getRemoteAddress() is a cluster member...
    }
    // customize Connection
    huc.setDoInput(true);

    // client->server
    int client2ServerTotal = 0;
    {
        if (hasContent) {
            huc.setDoOutput(true);

            OutputStream toServer = null;
            try {
                InputStream fromClient = req.getInputStream(); // IOException
                toServer = huc.getOutputStream(); // IOException
                client2ServerTotal = copy(fromClient, toServer, 8192);
            } catch (IOException e) {
                new IrrecoverableException("problem proxying client request to server", e);
            } finally {
                if (toServer != null) {
                    try {
                        toServer.close(); // IOException
                    } catch (IOException e) {
                        _log.warn("problem closing server request stream", e);
                    }
                }
            }
        }
    }

    // Connect
    try {
        huc.connect(); // IOException
    } catch (IOException e) {
        if (_log.isWarnEnabled())
            _log.warn("proxy connection problem: " + url, e);
        throw new RecoverableException("could not connect to proxy target", e);
    }

    InputStream fromServer = null;

    // handler status codes etc.
    int code = 0;
    if (huc == null) {
        try {
            fromServer = huc.getInputStream(); // IOException
        } catch (IOException e) {
            if (_log.isWarnEnabled())
                _log.warn("proxying problem", e);
            throw new IrrecoverableException("problem acquiring client output", e);
        }
    } else {
        code = 502;
        //         String message="Bad Gateway: could not read server response code or message";
        try {
            code = huc.getResponseCode(); // IOException
            //            message=huc.getResponseMessage(); // IOException
        } catch (IOException e) {
            if (_log.isWarnEnabled())
                _log.warn("proxying problem", e);
            throw new IrrecoverableException("problem acquiring http server response code/message", e);
        } finally {
            //            res.setStatus(code, message); - deprecated
            res.setStatus(code);
        }

        if (code < 400) {
            // 1XX:continue, 2XX:successful, 3XX:multiple-choices...
            try {
                fromServer = huc.getInputStream(); // IOException
            } catch (IOException e) {
                if (_log.isWarnEnabled())
                    _log.warn("proxying problem", e);
                throw new IrrecoverableException("problem acquiring http client output", e);
            }
        } else {
            // 4XX:client, 5XX:server error...
            fromServer = huc.getErrorStream(); // why does this not throw IOException ?
            // TODO - do we need to use sendError()?
        }
    }

    // clear response defaults.
    res.setHeader("Date", null);
    res.setHeader("Server", null);

    // set response headers
    if (false) {
        int h = 0;
        String hdr = huc.getHeaderFieldKey(h);
        String val = huc.getHeaderField(h);
        while (hdr != null || val != null) {
            String lhdr = (hdr != null) ? hdr.toLowerCase() : null;
            if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr))
                res.addHeader(hdr, val);

            // if (_log.isDebugEnabled()) _log.debug("res " + hdr + ": " + val);

            h++;
            hdr = huc.getHeaderFieldKey(h);
            val = huc.getHeaderField(h);
        }
    } else {
        // TODO - is it a bug in Jetty that I have to start my loop at 1 ? or that key[0]==null ?
        // Try this inside Tomcat...
        String key;
        for (int i = 1; (key = huc.getHeaderFieldKey(i)) != null; i++) {
            key = key.toLowerCase();
            String val = huc.getHeaderField(i);
            if (val != null && !_DontProxyHeaders.contains(key)) {
                res.addHeader(key, val);
            }
        }
    }

    // do we need another Via header in the response...

    // server->client
    int server2ClientTotal = 0;
    {
        if (fromServer != null) {
            try {
                OutputStream toClient = res.getOutputStream();// IOException
                server2ClientTotal += copy(fromServer, toClient, 8192);// IOException
            } catch (IOException e) {
                if (_log.isWarnEnabled())
                    _log.warn("proxying problem", e);
                throw new IrrecoverableException("problem proxying server response back to client", e);
            } finally {
                try {
                    fromServer.close();
                } catch (IOException e) {
                    // well - we did our best...
                    _log.warn("problem closing server response stream", e);
                }
            }
        }
    }

    huc.disconnect();

    long endTime = System.currentTimeMillis();
    long elapsed = endTime - startTime;
    if (_log.isDebugEnabled())
        _log.debug("in:" + client2ServerTotal + ", out:" + server2ClientTotal + ", status:" + code + ", time:"
                + elapsed + ", url:" + url);
}