Example usage for java.net URLConnection setDoOutput

List of usage examples for java.net URLConnection setDoOutput

Introduction

In this page you can find the example usage for java.net URLConnection setDoOutput.

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

Sets the value of the doOutput field for this URLConnection to the specified value.

Usage

From source file:org.openqa.selenium.server.ProxyHandler.java

protected long proxyPlainTextRequest(URL url, String pathInContext, String pathParams, HttpRequest request,
        HttpResponse response) throws IOException {
    CaptureNetworkTrafficCommand.Entry entry = new CaptureNetworkTrafficCommand.Entry(request.getMethod(),
            url.toString());//from  w w w  .j ava  2 s. c  o  m
    entry.addRequestHeaders(request);

    if (log.isDebugEnabled())
        log.debug("PROXY URL=" + url);

    URLConnection connection = url.openConnection();
    connection.setAllowUserInteraction(false);

    if (proxyInjectionMode) {
        adjustRequestForProxyInjection(request, connection);
    }

    // Set method
    HttpURLConnection http = null;
    if (connection instanceof HttpURLConnection) {
        http = (HttpURLConnection) connection;
        http.setRequestMethod(request.getMethod());
        http.setInstanceFollowRedirects(false);
        if (trustAllSSLCertificates && connection instanceof HttpsURLConnection) {
            TrustEverythingSSLTrustManager.trustAllSSLCertificates((HttpsURLConnection) connection);
        }
    }

    // check connection header
    String connectionHdr = request.getField(HttpFields.__Connection);
    if (connectionHdr != null && (connectionHdr.equalsIgnoreCase(HttpFields.__KeepAlive)
            || connectionHdr.equalsIgnoreCase(HttpFields.__Close)))
        connectionHdr = null;

    // copy headers
    boolean xForwardedFor = false;
    boolean isGet = "GET".equals(request.getMethod());
    boolean hasContent = false;
    Enumeration enm = request.getFieldNames();
    while (enm.hasMoreElements()) {
        // TODO could be better than this!
        String hdr = (String) enm.nextElement();

        if (_DontProxyHeaders.containsKey(hdr) || !_chained && _ProxyAuthHeaders.containsKey(hdr))
            continue;
        if (connectionHdr != null && connectionHdr.indexOf(hdr) >= 0)
            continue;

        if (!isGet && HttpFields.__ContentType.equals(hdr))
            hasContent = true;

        Enumeration vals = request.getFieldValues(hdr);
        while (vals.hasMoreElements()) {
            String val = (String) vals.nextElement();
            if (val != null) {
                // don't proxy Referer headers if the referer is Selenium!
                if ("Referer".equals(hdr) && (-1 != val.indexOf("/selenium-server/"))) {
                    continue;
                }
                if (!isGet && HttpFields.__ContentLength.equals(hdr) && Integer.parseInt(val) > 0) {
                    hasContent = true;
                }

                connection.addRequestProperty(hdr, val);
                xForwardedFor |= HttpFields.__XForwardedFor.equalsIgnoreCase(hdr);
            }
        }
    }

    // add any custom request headers that the user asked for
    Map<String, String> customRequestHeaders = AddCustomRequestHeaderCommand.getHeaders();
    for (Map.Entry<String, String> e : customRequestHeaders.entrySet()) {
        connection.addRequestProperty(e.getKey(), e.getValue());
        entry.addRequestHeader(e.getKey(), e.getValue());
    }

    // Proxy headers
    if (!_anonymous)
        connection.setRequestProperty("Via", "1.1 (jetty)");
    if (!xForwardedFor)
        connection.addRequestProperty(HttpFields.__XForwardedFor, request.getRemoteAddr());

    // a little bit of cache control
    String cache_control = request.getField(HttpFields.__CacheControl);
    if (cache_control != null
            && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0))
        connection.setUseCaches(false);

    // customize Connection
    customizeConnection(pathInContext, pathParams, request, connection);

    try {
        connection.setDoInput(true);

        // do input thang!
        InputStream in = request.getInputStream();
        if (hasContent) {
            connection.setDoOutput(true);
            IO.copy(in, connection.getOutputStream());
        }

        // Connect
        connection.connect();
    } catch (Exception e) {
        LogSupport.ignore(log, e);
    }

    InputStream proxy_in = null;

    // handler status codes etc.
    int code = -1;
    if (http != null) {
        proxy_in = http.getErrorStream();

        try {
            code = http.getResponseCode();
        } catch (SSLHandshakeException e) {
            throw new RuntimeException("Couldn't establish SSL handshake.  Try using trustAllSSLCertificates.\n"
                    + e.getLocalizedMessage(), e);
        }
        response.setStatus(code);
        response.setReason(http.getResponseMessage());

        String contentType = http.getContentType();
        if (log.isDebugEnabled()) {
            log.debug("Content-Type is: " + contentType);
        }
    }

    if (proxy_in == null) {
        try {
            proxy_in = connection.getInputStream();
        } catch (Exception e) {
            LogSupport.ignore(log, e);
            proxy_in = http.getErrorStream();
        }
    }

    // clear response defaults.
    response.removeField(HttpFields.__Date);
    response.removeField(HttpFields.__Server);

    // set response headers
    int h = 0;
    String hdr = connection.getHeaderFieldKey(h);
    String val = connection.getHeaderField(h);
    while (hdr != null || val != null) {
        if (hdr != null && val != null && !_DontProxyHeaders.containsKey(hdr)
                && (_chained || !_ProxyAuthHeaders.containsKey(hdr)))
            response.addField(hdr, val);
        h++;
        hdr = connection.getHeaderFieldKey(h);
        val = connection.getHeaderField(h);
    }
    if (!_anonymous)
        response.setField("Via", "1.1 (jetty)");

    response.removeField(HttpFields.__ETag); // possible cksum?  Stop caching...
    response.removeField(HttpFields.__LastModified); // Stop caching...

    // Handled
    long bytesCopied = -1;
    request.setHandled(true);
    if (proxy_in != null) {
        boolean injectableResponse = http.getResponseCode() == HttpURLConnection.HTTP_OK
                || (http.getResponseCode() >= 400 && http.getResponseCode() < 600);
        if (proxyInjectionMode && injectableResponse) {
            // check if we should proxy this path based on the dontProxyRegex that can be user-specified
            if (shouldInject(request.getPath())) {
                bytesCopied = InjectionHelper.injectJavaScript(request, response, proxy_in,
                        response.getOutputStream(), debugURL);
            } else {
                bytesCopied = ModifiedIO.copy(proxy_in, response.getOutputStream());
            }
        } else {
            bytesCopied = ModifiedIO.copy(proxy_in, response.getOutputStream());
        }
    }

    entry.finish(code, bytesCopied);
    entry.addResponseHeader(response);

    CaptureNetworkTrafficCommand.capture(entry);

    return bytesCopied;
}

From source file:org.regenstrief.util.Util.java

public final static String post(final String url, final String content) throws IOException {
    final URLConnection ucon = new URL(url).openConnection();

    ucon.setDoInput(true);/*  w  ww  .ja v  a 2 s  .c  o m*/
    if (content != null) {
        ucon.setDoOutput(true);
        ucon.getOutputStream().write(content.getBytes());
    }

    return readStream(getRawStream(ucon));
}

From source file:com.codename1.impl.android.AndroidImplementation.java

public Object connect(String url, boolean read, boolean write, int timeout) throws IOException {
    URL u = new URL(url);
    CookieHandler.setDefault(null);
    URLConnection con = u.openConnection();
    if (con instanceof HttpURLConnection) {
        HttpURLConnection c = (HttpURLConnection) con;
        c.setUseCaches(false);//from  w w w. j  ava 2s .  c o  m
        c.setDefaultUseCaches(false);
        c.setInstanceFollowRedirects(false);
        if (timeout > -1) {
            c.setConnectTimeout(timeout);
        }
        if (read) {
            if (timeout > -1) {
                c.setReadTimeout(timeout);
            } else {
                c.setReadTimeout(10000);
            }
        }
        if (android.os.Build.VERSION.SDK_INT > 13) {
            c.setRequestProperty("Connection", "close");
        }
    }
    con.setDoInput(read);
    con.setDoOutput(write);
    return con;
}