Example usage for java.net HttpURLConnection setUseCaches

List of usage examples for java.net HttpURLConnection setUseCaches

Introduction

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

Prototype

public void setUseCaches(boolean usecaches) 

Source Link

Document

Sets the value of the useCaches field of this URLConnection to the specified value.

Usage

From source file:count.ly.messaging.ConnectionProcessor.java

URLConnection urlConnectionForEventData(final String eventData) throws IOException {
    String urlStr = serverURL_ + "/i?";
    if (!eventData.contains("&crash="))
        urlStr += eventData;//from   w  w  w.jav  a2s.  c o  m
    final URL url = new URL(urlStr);
    final HttpURLConnection conn;
    if (Countly.publicKeyPinCertificates == null) {
        conn = (HttpURLConnection) url.openConnection();
    } else {
        HttpsURLConnection c = (HttpsURLConnection) url.openConnection();
        c.setSSLSocketFactory(sslContext_.getSocketFactory());
        conn = c;
    }
    conn.setConnectTimeout(CONNECT_TIMEOUT_IN_MILLISECONDS);
    conn.setReadTimeout(READ_TIMEOUT_IN_MILLISECONDS);
    conn.setUseCaches(false);
    conn.setDoInput(true);
    String picturePath = UserData.getPicturePathFromQuery(url);
    if (Countly.sharedInstance().isLoggingEnabled()) {
        Log.d(Countly.TAG, "Got picturePath: " + picturePath);
    }
    if (!picturePath.equals("")) {
        //Uploading files:
        //http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests

        File binaryFile = new File(picturePath);
        conn.setDoOutput(true);
        // Just generate some unique random value.
        String boundary = Long.toHexString(System.currentTimeMillis());
        // Line separator required by multipart/form-data.
        String CRLF = "\r\n";
        String charset = "UTF-8";
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        OutputStream output = conn.getOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
        // Send binary file.
        writer.append("--" + boundary).append(CRLF);
        writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName()
                + "\"").append(CRLF);
        writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName()))
                .append(CRLF);
        writer.append("Content-Transfer-Encoding: binary").append(CRLF);
        writer.append(CRLF).flush();
        FileInputStream fileInputStream = new FileInputStream(binaryFile);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fileInputStream.read(buffer)) != -1) {
            output.write(buffer, 0, len);
        }
        output.flush(); // Important before continuing with writer!
        writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
        fileInputStream.close();

        // End of multipart/form-data.
        writer.append("--" + boundary + "--").append(CRLF).flush();
    } else if (eventData.contains("&crash=")) {
        if (Countly.sharedInstance().isLoggingEnabled()) {
            Log.d(Countly.TAG, "Using post because of crash");
        }
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(eventData);
        writer.flush();
        writer.close();
        os.close();
    } else {
        conn.setDoOutput(false);
    }
    return conn;
}

From source file:com.cts.ptms.carrier.ups.UPSHTTPClient.java

/**
 * This method establish the connection to the REST service
 *///from  ww w .  j  a va  2  s .co  m
private String contactService(String xmlInputString, String serviceUrl) throws Exception {
    String outputStr = null;
    OutputStream outputStream = null;
    try {

        URL url = new URL(serviceUrl);
        //System.getProperties().put("https.proxyHost", "proxy.cognizant.com");
        // System.getProperties().put("https.proxyPort", "6050"); 
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //   connection.setRequestProperty("User-Agent", "Mozilla/4.5");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        xmlInputString = xmlInputString.replace(ShippingConstants.XML_STANDALONE_STRING, "");
        outputStream = connection.getOutputStream();
        outputStream.write(xmlInputString.getBytes());
        outputStream.flush();
        outputStream.close();
        outputStr = readURLConnection(connection);
    } catch (Exception e) {
        throw e;
    } finally {
        if (outputStream != null) {
            outputStream.close();
            outputStream = null;
        }
    }
    return outputStr;
}

From source file:com.amazonaws.http.UrlHttpClient.java

void configureConnection(HttpRequest request, HttpURLConnection connection) {
    // configure the connection
    connection.setConnectTimeout(config.getConnectionTimeout());
    connection.setReadTimeout(config.getSocketTimeout());
    // disable redirect and cache
    connection.setInstanceFollowRedirects(false);
    connection.setUseCaches(false);
    // is streaming
    if (request.isStreaming()) {
        connection.setChunkedStreamingMode(0);
    }/*w ww. j a  v  a 2s. co m*/

    // configure https connection
    if (connection instanceof HttpsURLConnection) {
        final HttpsURLConnection https = (HttpsURLConnection) connection;

        // disable cert check
        /*
         * Commented as per https://support.google.com/faqs/answer/6346016. Uncomment for testing.
        if (System.getProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) {
        disableCertificateValidation(https);
        }
        */

        if (config.getTrustManager() != null) {
            enableCustomTrustManager(https);
        }
    }
}

From source file:com.docdoku.cli.helpers.FileHelper.java

public String downloadFile(File pLocalFile, String pURL)
        throws IOException, LoginException, NoSuchAlgorithmException {
    ConsoleProgressMonitorInputStream in = null;
    OutputStream out = null;/*from  w  w w .  j a  v a2 s.  co m*/
    HttpURLConnection conn = null;
    try {
        //Hack for NTLM proxy
        //perform a head method to negociate the NTLM proxy authentication
        URL url = new URL(pURL);
        System.out.println("Downloading file: " + pLocalFile.getName() + " from " + url.getHost());
        performHeadHTTPMethod(url);

        out = new BufferedOutputStream(new FileOutputStream(pLocalFile), BUFFER_CAPACITY);

        conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestMethod("GET");
        byte[] encoded = Base64.encodeBase64((login + ":" + password).getBytes("ISO-8859-1"));
        conn.setRequestProperty("Authorization", "Basic " + new String(encoded, "US-ASCII"));
        conn.connect();
        manageHTTPCode(conn);

        MessageDigest md = MessageDigest.getInstance("MD5");
        in = new ConsoleProgressMonitorInputStream(conn.getContentLength(),
                new DigestInputStream(new BufferedInputStream(conn.getInputStream(), BUFFER_CAPACITY), md));
        byte[] data = new byte[CHUNK_SIZE];
        int length;

        while ((length = in.read(data)) != -1) {
            out.write(data, 0, length);
        }
        out.flush();

        byte[] digest = md.digest();
        return Base64.encodeBase64String(digest);
    } finally {
        if (out != null)
            out.close();
        if (in != null)
            in.close();
        if (conn != null)
            conn.disconnect();
    }
}

From source file:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java

protected boolean uploadFile(File fileToUpload) {
    String lineEnding = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    boolean success = true;
    HttpURLConnection connection = null;
    try {//from   w  w w.  j av  a2s . co  m
        URL dest = new URL("http://mouflon.csc.ncsu.edu/cgi-bin/upload.cgi");
        connection = (HttpURLConnection) dest.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        connection.setChunkedStreamingMode(0);
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes(twoHyphens + boundary + lineEnding);
        //Log.i("uploadFile", fileToUpload.getName());
        out.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""
                + fileToUpload.getName() + "\"" + lineEnding);
        out.writeBytes("Content-Type: application/octet-stream" + lineEnding);
        out.writeBytes("Content-Transfer-Encoding: base64" + lineEnding);
        out.writeBytes(lineEnding);
        encodeFileBase64(fileToUpload, out); //TODO this works fine for small files but for some file size between 256k and 2M it begins failing.

        out.writeBytes(lineEnding);
        out.writeBytes(twoHyphens + boundary + twoHyphens + lineEnding);
        //Log.i("UploadTest", "File uploaded");
        out.flush();
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
        success = false;
    }
    try {
        BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
        byte[] resp = new byte[80];
        int read = 0;
        if ((read = in.read(resp)) > 0) {
            String responseString = new String(resp, 0, read);
            //Log.i("uploadFile", responseString);
            if (!responseString.equals(fileToUpload.getName())) {
                //Log.e("Upload", "File upload failed");
            }
        }
        //else 
        //Log.e("Upload", "No response received from server");

    } catch (Exception e) {
        e.printStackTrace();
        success = false;
    }
    return success;
}

From source file:net.ymate.module.webproxy.WebProxy.java

@SuppressWarnings("unchecked")
public void transmission(HttpServletRequest request, HttpServletResponse response, String url,
        Type.HttpMethod method) throws Exception {
    StopWatch _consumeTime = null;//w  w  w . ja v a  2 s .c  o m
    long _threadId = 0;
    if (_LOG.isDebugEnabled()) {
        _consumeTime = new StopWatch();
        _consumeTime.start();
        _threadId = Thread.currentThread().getId();
        _LOG.debug("-------------------------------------------------");
        _LOG.debug("--> [" + _threadId + "] URL: " + url);
    }
    //
    HttpURLConnection _conn = null;
    try {
        if (__moduleCfg.isUseProxy()) {
            _conn = (HttpURLConnection) new URL(url).openConnection(__moduleCfg.getProxy());
        } else {
            _conn = (HttpURLConnection) new URL(url).openConnection();
        }
        _conn.setUseCaches(__moduleCfg.isUseCaches());
        _conn.setInstanceFollowRedirects(__moduleCfg.isInstanceFollowRedirects());
        //
        boolean _postFlag = Type.HttpMethod.POST.equals(method);
        boolean _multipartFlag = _postFlag && StringUtils.contains(request.getContentType(), "multipart/");
        if (_postFlag) {
            _conn.setDoOutput(true);
            _conn.setDoInput(true);
            _conn.setRequestMethod(method.name());
        }
        if (__moduleCfg.getConnectTimeout() > 0) {
            _conn.setConnectTimeout(__moduleCfg.getConnectTimeout());
        }
        if (__moduleCfg.getReadTimeout() > 0) {
            _conn.setReadTimeout(__moduleCfg.getReadTimeout());
        }
        //
        if (_LOG.isDebugEnabled()) {
            _LOG.debug("--> [" + _threadId + "] Method: " + method.name());
            _LOG.debug("--> [" + _threadId + "] Request Headers: ");
        }
        //
        Enumeration _header = request.getHeaderNames();
        while (_header.hasMoreElements()) {
            String _name = (String) _header.nextElement();
            String _value = request.getHeader(_name);
            boolean _flag = false;
            if (_postFlag && StringUtils.equalsIgnoreCase(_name, "content-type")
                    || __moduleCfg.isTransferHeaderEnabled()
                            && (!__moduleCfg.getTransferHeaderBlackList().isEmpty()
                                    && !__moduleCfg.getTransferHeaderBlackList().contains(_name)
                                    || !__moduleCfg.getTransferHeaderWhiteList().isEmpty()
                                            && __moduleCfg.getTransferHeaderWhiteList().contains(_name))) {
                _conn.setRequestProperty(_name, _value);
                _flag = true;
            }
            //
            if (_LOG.isDebugEnabled()) {
                _LOG.debug("--> [" + _threadId + "] \t " + (_flag ? " - " : " > ") + _name + ": " + _value);
            }
        }
        _conn.connect();
        //
        if (_postFlag) {
            DataOutputStream _output = new DataOutputStream(_conn.getOutputStream());
            try {
                if (_multipartFlag) {
                    if (_LOG.isDebugEnabled()) {
                        _LOG.debug("--> [" + _threadId + "] Multipart: TRUE");
                    }
                    IOUtils.copyLarge(request.getInputStream(), _output);
                } else {
                    String _charset = request.getCharacterEncoding();
                    String _queryStr = ParamUtils.buildQueryParamStr(request.getParameterMap(), true, _charset);
                    IOUtils.write(_queryStr, _output, _charset);
                    //
                    if (_LOG.isDebugEnabled()) {
                        _LOG.debug("--> [" + _threadId + "] Request Parameters: ");
                        Map<String, String> _paramsMap = ParamUtils.parseQueryParamStr(_queryStr, true,
                                _charset);
                        for (Map.Entry<String, String> _param : _paramsMap.entrySet()) {
                            _LOG.debug("--> [" + _threadId + "] \t - " + _param.getKey() + ": "
                                    + _param.getValue());
                        }
                    }
                }
                _output.flush();
            } finally {
                IOUtils.closeQuietly(_output);
            }
        }
        //
        int _code = _conn.getResponseCode();
        //
        if (_LOG.isDebugEnabled()) {
            _LOG.debug("--> [" + _threadId + "] Response Code: " + _code);
            _LOG.debug("--> [" + _threadId + "] Response Headers: ");
        }
        //
        Map<String, List<String>> _headers = _conn.getHeaderFields();
        for (Map.Entry<String, List<String>> _entry : _headers.entrySet()) {
            if (_entry.getKey() != null) {
                boolean _flag = false;
                String _values = StringUtils.join(_entry.getValue(), ",");
                if (StringUtils.equalsIgnoreCase(_entry.getKey(), "content-type")
                        || __moduleCfg.isTransferHeaderEnabled()
                                && !__moduleCfg.getResponseHeaderWhileList().isEmpty()
                                && __moduleCfg.getResponseHeaderWhileList().contains(_entry.getKey())) {
                    response.setHeader(_entry.getKey(), _values);
                    _flag = true;
                }
                if (_LOG.isDebugEnabled()) {
                    _LOG.debug("--> [" + _threadId + "] \t " + (_flag ? " - " : " > ") + _entry.getKey() + ": "
                            + _values);
                }
            }
        }
        if (HttpURLConnection.HTTP_BAD_REQUEST <= _conn.getResponseCode()) {
            response.sendError(_code);
        } else {
            if (HttpURLConnection.HTTP_OK == _code) {
                InputStream _inputStream = _conn.getInputStream();
                if (_inputStream != null) {
                    if (!_multipartFlag) {
                        byte[] _content = IOUtils.toByteArray(_inputStream);
                        IOUtils.write(_content, response.getOutputStream());
                        //
                        if (_LOG.isDebugEnabled()) {
                            _LOG.debug("--> [" + _threadId + "] Response Content: " + __doParseContentBody(
                                    _conn, _content, WebMVC.get().getModuleCfg().getDefaultCharsetEncoding()));
                        }
                    } else {
                        IOUtils.copyLarge(_conn.getInputStream(), response.getOutputStream());
                        //
                        if (_LOG.isDebugEnabled()) {
                            _LOG.debug("--> [" + _threadId + "] Response Content: MultipartBody");
                        }
                    }
                } else if (_LOG.isDebugEnabled()) {
                    _LOG.debug("--> [" + _threadId + "] Response Content: NULL");
                }
                response.flushBuffer();
            } else {
                InputStream _inputStream = _conn.getInputStream();
                if (_inputStream != null) {
                    byte[] _content = IOUtils.toByteArray(_inputStream);
                    IOUtils.write(_content, response.getOutputStream());
                    //
                    if (_LOG.isDebugEnabled()) {
                        _LOG.debug("--> [" + _threadId + "] Response Content: " + __doParseContentBody(_conn,
                                _content, WebMVC.get().getModuleCfg().getDefaultCharsetEncoding()));
                    }
                } else if (_LOG.isDebugEnabled()) {
                    _LOG.debug("--> [" + _threadId + "] Response Content: NULL");
                }
                response.setStatus(_code);
                response.flushBuffer();
            }
        }
    } catch (Throwable e) {
        _LOG.warn("An exception occurred while processing request mapping '" + url + "': ",
                RuntimeUtils.unwrapThrow(e));
    } finally {
        IOUtils.close(_conn);
        //
        if (_LOG.isDebugEnabled()) {
            if (_consumeTime != null) {
                _consumeTime.stop();
                _LOG.debug("--> [" + _threadId + "] Total execution time: " + _consumeTime.getTime() + "ms");
            }
            _LOG.debug("-------------------------------------------------");
        }
    }
}

From source file:edu.stanford.junction.sample.partyware.ImgurUploadService.java

/**
 * This method uploads an image from the given uri. It does the uploading in
 * small chunks to make sure it doesn't over run the memory.
 * /*  w  ww  .ja  va  2 s .c o  m*/
 * @param uri
 *            image location
 * @return map containing data from interaction
 */
private String readPictureDataAndUpload(final Uri uri) {
    Log.i(this.getClass().getName(), "in readPictureDataAndUpload(Uri)");
    try {
        final AssetFileDescriptor assetFileDescriptor = getContentResolver().openAssetFileDescriptor(uri, "r");
        final int totalFileLength = (int) assetFileDescriptor.getLength();
        assetFileDescriptor.close();

        // Create custom progress notification
        mProgressNotification = new Notification(R.drawable.icon, getString(R.string.imgur_upload_in_progress),
                System.currentTimeMillis());
        // set as ongoing
        mProgressNotification.flags |= Notification.FLAG_ONGOING_EVENT;
        // set custom view to notification
        mProgressNotification.contentView = generateProgressNotificationView(0, totalFileLength);
        //empty intent for the notification
        final Intent progressIntent = new Intent();
        final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, progressIntent, 0);
        mProgressNotification.contentIntent = contentIntent;
        // add notification to manager
        mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification);

        final InputStream inputStream = getContentResolver().openInputStream(uri);

        final String boundaryString = "Z." + Long.toHexString(System.currentTimeMillis())
                + Long.toHexString((new Random()).nextLong());
        final String boundary = "--" + boundaryString;
        final HttpURLConnection conn = (HttpURLConnection) (new URL("http://imgur.com/api/upload.json"))
                .openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-type", "multipart/form-data; boundary=\"" + boundaryString + "\"");
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setChunkedStreamingMode(CHUNK_SIZE);
        final OutputStream hrout = conn.getOutputStream();
        final PrintStream hout = new PrintStream(hrout);
        hout.println(boundary);
        hout.println("Content-Disposition: form-data; name=\"key\"");
        hout.println("Content-Type: text/plain");
        hout.println();

        Random rng = new Random();
        String key = API_KEYS[rng.nextInt(API_KEYS.length)];
        hout.println(key);

        hout.println(boundary);
        hout.println("Content-Disposition: form-data; name=\"image\"");
        hout.println("Content-Transfer-Encoding: base64");
        hout.println();
        hout.flush();
        {
            final Base64OutputStream bhout = new Base64OutputStream(hrout);
            final byte[] pictureData = new byte[READ_BUFFER_SIZE_BYTES];
            int read = 0;
            int totalRead = 0;
            long lastLogTime = 0;
            while (read >= 0) {
                read = inputStream.read(pictureData);
                if (read > 0) {
                    bhout.write(pictureData, 0, read);
                    totalRead += read;
                    if (lastLogTime < (System.currentTimeMillis() - PROGRESS_UPDATE_INTERVAL_MS)) {
                        lastLogTime = System.currentTimeMillis();
                        Log.d(this.getClass().getName(), "Uploaded " + totalRead + " of " + totalFileLength
                                + " bytes (" + (100 * totalRead) / totalFileLength + "%)");

                        //make a final version of the total read to make the handler happy
                        final int totalReadFinal = totalRead;
                        mHandler.post(new Runnable() {
                            public void run() {
                                mProgressNotification.contentView = generateProgressNotificationView(
                                        totalReadFinal, totalFileLength);
                                mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification);
                            }
                        });
                    }
                    bhout.flush();
                    hrout.flush();
                }
            }
            Log.d(this.getClass().getName(), "Finishing upload...");
            // This close is absolutely necessary, this tells the
            // Base64OutputStream to finish writing the last of the data
            // (and including the padding). Without this line, it will miss
            // the last 4 chars in the output, missing up to 3 bytes in the
            // final output.
            bhout.close();
            Log.d(this.getClass().getName(), "Upload complete...");
            mProgressNotification.contentView.setProgressBar(R.id.UploadProgress, totalFileLength, totalRead,
                    false);
            mNotificationManager.cancelAll();
        }

        hout.println(boundary);
        hout.flush();
        hrout.close();

        inputStream.close();

        Log.d(this.getClass().getName(), "streams closed, " + "now waiting for response from server");

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final StringBuilder rData = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            rData.append(line).append('\n');
        }

        return rData.toString();
    } catch (final IOException e) {
        Log.e(this.getClass().getName(), "Upload failed", e);
    }

    return null;
}

From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java

protected Response invoke(UrlBuilder url, String method, String contentType, Map<String, String> headers,
        Output writer, BindingSession session, BigInteger offset, BigInteger length) {
    try {/*from  www.j av a 2s.  c o m*/
        // log before connect
        //Log.d("URL", url.toString());
        if (LOG.isDebugEnabled()) {
            LOG.debug(method + " " + url);
        }

        // connect
        HttpURLConnection conn = getHttpURLConnection(new URL(url.toString()));
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(writer != null);
        conn.setAllowUserInteraction(false);
        conn.setUseCaches(false);
        conn.setRequestProperty(HTTP.USER_AGENT, ClientVersion.OPENCMIS_CLIENT);

        // timeouts
        int connectTimeout = session.get(SessionParameter.CONNECT_TIMEOUT, -1);
        if (connectTimeout >= 0) {
            conn.setConnectTimeout(connectTimeout);
        }

        int readTimeout = session.get(SessionParameter.READ_TIMEOUT, -1);
        if (readTimeout >= 0) {
            conn.setReadTimeout(readTimeout);
        }

        // set content type
        if (contentType != null) {
            conn.setRequestProperty(HTTP.CONTENT_TYPE, contentType);
        }
        // set other headers
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                conn.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // authenticate
        AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session);
        if (authProvider != null) {
            Map<String, List<String>> httpHeaders = authProvider.getHTTPHeaders(url.toString());
            if (httpHeaders != null) {
                for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) {
                    if (header.getValue() != null) {
                        for (String value : header.getValue()) {
                            conn.addRequestProperty(header.getKey(), value);
                        }
                    }
                }
            }

            if (conn instanceof HttpsURLConnection) {
                SSLSocketFactory sf = authProvider.getSSLSocketFactory();
                if (sf != null) {
                    ((HttpsURLConnection) conn).setSSLSocketFactory(sf);
                }

                HostnameVerifier hv = authProvider.getHostnameVerifier();
                if (hv != null) {
                    ((HttpsURLConnection) conn).setHostnameVerifier(hv);
                }
            }
        }

        // range
        if ((offset != null) || (length != null)) {
            StringBuilder sb = new StringBuilder("bytes=");

            if ((offset == null) || (offset.signum() == -1)) {
                offset = BigInteger.ZERO;
            }

            sb.append(offset.toString());
            sb.append("-");

            if ((length != null) && (length.signum() == 1)) {
                sb.append(offset.add(length.subtract(BigInteger.ONE)).toString());
            }

            conn.setRequestProperty("Range", sb.toString());
        }

        // compression
        Object compression = session.get(AlfrescoSession.HTTP_ACCEPT_ENCODING);
        if (compression == null) {
            conn.setRequestProperty("Accept-Encoding", "");
        } else {
            Boolean compressionValue;
            try {
                compressionValue = Boolean.parseBoolean(compression.toString());
                if (compressionValue) {
                    conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
                } else {
                    conn.setRequestProperty("Accept-Encoding", "");
                }
            } catch (Exception e) {
                conn.setRequestProperty("Accept-Encoding", compression.toString());
            }
        }

        // locale
        if (session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) instanceof String
                && session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) != null) {
            conn.setRequestProperty("Accept-Language",
                    session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE).toString());
        }

        // send data
        if (writer != null) {
            Object chunkTransfert = session.get(AlfrescoSession.HTTP_CHUNK_TRANSFERT);
            if (chunkTransfert != null && Boolean.parseBoolean(chunkTransfert.toString())) {
                conn.setRequestProperty(HTTP.TRANSFER_ENCODING, "chunked");
                conn.setChunkedStreamingMode(0);
            }

            conn.setConnectTimeout(900000);

            OutputStream connOut = null;

            Object clientCompression = session.get(SessionParameter.CLIENT_COMPRESSION);
            if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                conn.setRequestProperty(HTTP.CONTENT_ENCODING, "gzip");
                connOut = new GZIPOutputStream(conn.getOutputStream(), 4096);
            } else {
                connOut = conn.getOutputStream();
            }

            OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE);
            writer.write(out);
            out.flush();
        }

        // connect
        conn.connect();

        // get stream, if present
        int respCode = conn.getResponseCode();
        InputStream inputStream = null;
        if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED)
                || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION)
                || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) {
            inputStream = conn.getInputStream();
        }

        // log after connect
        if (LOG.isTraceEnabled()) {
            LOG.trace(method + " " + url + " > Headers: " + conn.getHeaderFields());
        }

        // forward response HTTP headers
        if (authProvider != null) {
            authProvider.putResponseHeaders(url.toString(), respCode, conn.getHeaderFields());
        }

        // get the response
        return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream,
                conn.getErrorStream());
    } catch (Exception e) {
        throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e);
    }
}

From source file:com.synelixis.xifi.AuthWebClient.Client.java

private String postURL(String url_, String data_, String credentials_) {
    String urlString = url_;/*w w  w. j  av a2  s .c  o  m*/
    String JSON = data_;
    String credentials = credentials_;

    try {
        URL u = new URL(urlString);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setDoOutput(true);
        c.setRequestMethod("POST");
        if ((credentials != null) && !credentials.equals("")) {
            c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            c.setRequestProperty("Authorization", "Basic " + credentials);
        } else {
            c.setRequestProperty("Content-Type", "application/json");
            c.setRequestProperty("Accept", "application/json");
        }
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        OutputStreamWriter out = new OutputStreamWriter(c.getOutputStream());
        out.write(JSON);
        out.flush();
        out.close();
        System.out.println("url:" + url_ + " -- data:" + data_ + " -- response" + c.getResponseCode());
        switch (c.getResponseCode()) {
        case 200:
        case 201:
            BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            String result = sb.toString();
            return result;
        }
    } catch (MalformedURLException ex) {
        Logger.getLogger(com.synelixis.xifi.AuthWebClient.Client.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(com.synelixis.xifi.AuthWebClient.Client.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(com.synelixis.xifi.AuthWebClient.Client.class.getName()).log(Level.SEVERE,
                "Unexpected exception when call the remote server ", ex);
    }
    return null;
}

From source file:com.culvereq.vimp.networking.ConnectionHandler.java

public String login(String username, String password) throws IOException {
    URL requestURL = new URL(loginURL);
    HttpURLConnection connection = (HttpURLConnection) requestURL.openConnection();
    connection.setDoInput(true);//  w w  w. j a va  2  s.c  o m
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("charset", "utf-8");
    String urlParameters = "";
    urlParameters += "username=" + username;
    urlParameters += "&password=" + password;

    connection.setRequestProperty("Content-Length", "" + urlParameters.getBytes().length);
    connection.setUseCaches(false);
    OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    writer.write(urlParameters);
    writer.flush();
    writer.close();

    int responseCode = connection.getResponseCode();
    if (responseCode == 200) {
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString().trim();
    } else {
        return null;
    }
}