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:de.sjka.logstash.osgi.internal.LogstashSender.java

private void process(LogEntry logEntry) {
    if (logEntry.getLevel() <= getLogLevelConfig()) {
        if (!"true".equals(getConfig(LogstashConfig.ENABLED))) {
            return;
        }//from ww  w .j  av a  2 s . c  o m
        ;
        for (ILogstashFilter logstashFilter : logstashFilters) {
            if (!logstashFilter.apply(logEntry)) {
                return;
            }
        }
        String request = getConfig(LogstashConfig.URL);
        if (!request.endsWith("/")) {
            request += "/";
        }
        HttpURLConnection conn = null;
        try {
            JSONObject values = serializeLogEntry(logEntry);

            String payload = values.toJSONString();
            byte[] postData = payload.getBytes(StandardCharsets.UTF_8);

            String username = getConfig(LogstashConfig.USERNAME);
            String password = getConfig(LogstashConfig.PASSWORD);

            String authString = username + ":" + password;
            byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
            String authStringEnc = new String(authEncBytes);

            URL url = new URL(request);

            conn = (HttpURLConnection) url.openConnection();
            if (request.startsWith("https") && "true".equals(getConfig(LogstashConfig.SSL_NO_CHECK))) {
                if (sslSocketFactory != null) {
                    ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
                    ((HttpsURLConnection) conn).setHostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    });
                }
            }
            conn.setDoOutput(true);
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod("PUT");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("charset", "utf-8");
            conn.setReadTimeout(30 * SECONDS);
            conn.setConnectTimeout(30 * SECONDS);
            if (username != null && !"".equals(username)) {
                conn.setRequestProperty("Authorization", "Basic " + authStringEnc);
            }
            conn.setUseCaches(false);
            try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
                wr.write(postData);
                wr.flush();
                wr.close();
            }
            if (conn.getResponseCode() != 200) {
                throw new IOException(
                        "Got response " + conn.getResponseCode() + " - " + conn.getResponseMessage());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

}

From source file:com.appbase.androidquery.callback.AbstractAjaxCallback.java

private void httpMulti(String url, Map<String, String> headers, Map<String, Object> params, AjaxStatus status)
        throws IOException {

    AQUtility.debug("multipart", url);

    HttpURLConnection conn = null;
    DataOutputStream dos = null;//from w ww  .  j  a v  a2s  .  c  o  m

    URL u = new URL(url);
    conn = (HttpURLConnection) u.openConnection();

    conn.setInstanceFollowRedirects(false);

    conn.setConnectTimeout(NET_TIMEOUT * 4);

    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data;charset=utf-8;boundary=" + boundary);

    if (headers != null) {
        for (String name : headers.keySet()) {
            conn.setRequestProperty(name, headers.get(name));
        }
    }

    String cookie = makeCookie();
    if (cookie != null) {
        conn.setRequestProperty("Cookie", cookie);
    }

    if (ah != null) {
        ah.applyToken(this, conn);
    }

    dos = new DataOutputStream(conn.getOutputStream());

    for (Map.Entry<String, Object> entry : params.entrySet()) {

        writeObject(dos, entry.getKey(), entry.getValue());

    }

    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    dos.flush();
    dos.close();

    conn.connect();

    int code = conn.getResponseCode();
    String message = conn.getResponseMessage();

    byte[] data = null;

    String encoding = conn.getContentEncoding();
    String error = null;

    if (code < 200 || code >= 300) {

        error = new String(toData(encoding, conn.getErrorStream()), "UTF-8");

        AQUtility.debug("error", error);
    } else {

        data = toData(encoding, conn.getInputStream());
    }

    AQUtility.debug("response", code);

    if (data != null) {
        AQUtility.debug(data.length, url);
    }

    status.code(code).message(message).redirect(url).time(new Date()).data(data).error(error).client(null);

}

From source file:com.roamprocess1.roaming4world.ui.messages.MessageActivity.java

public int uploadFile(String sourceFileUri, String fileName) {

    String upLoadServerUri = "";
    upLoadServerUri = "http://ip.roaming4world.com/esstel/file-transfer/file_upload.php";

    HttpURLConnection conn = null;
    DataOutputStream dos = null;// w ww  . j  a  v a2  s  . c  o  m
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {
        Log.e("uploadFile", "Source File Does not exist");
        return 0;
    }
    try { // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);
        conn = (HttpURLConnection) url.openConnection(); // Open a HTTP
        // connection to
        // the URL
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        conn.setRequestProperty("uploaded_file", sourceFileUri);

        dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + multimediaMsg
                + fileName + "\"" + lineEnd);
        dos.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available(); // create a buffer of
        // maximum size

        bufferSize = Math.min(bytesAvailable, maxBufferSize);

        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // Responses from the server (code and message)
        serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

        Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);

        // close the streams //
        fileInputStream.close();
        dos.flush();
        dos.close();

    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
    }
    return serverResponseCode;

}

From source file:com.gotraveling.external.androidquery.callback.AbstractAjaxCallback.java

private void httpMulti(String url, Map<String, String> headers, Map<String, Object> params, AjaxStatus status)
        throws IOException {

    AQUtility.debug("multipart", url);

    HttpURLConnection conn = null;
    DataOutputStream dos = null;//  w  w w  . j  a  v a2s.  c  o  m

    URL u = new URL(url);
    conn = (HttpURLConnection) u.openConnection();

    conn.setInstanceFollowRedirects(false);

    conn.setConnectTimeout(NET_TIMEOUT * 4);

    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data;charset=utf-8;boundary=" + boundary);

    if (headers != null) {
        for (String name : headers.keySet()) {
            conn.setRequestProperty(name, headers.get(name));
        }
    }

    String cookie = makeCookie();
    if (cookie != null) {
        conn.setRequestProperty("Cookie", cookie);
    }

    if (ah != null) {
        ah.applyToken(this, conn);
    }

    dos = new DataOutputStream(conn.getOutputStream());

    Object o = null;

    if (progress != null) {
        o = progress.get();
    }

    Progress p = null;

    if (o != null) {
        p = new Progress(o);
    }

    for (Map.Entry<String, Object> entry : params.entrySet()) {

        writeObject(dos, entry.getKey(), entry.getValue(), p);

    }

    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    dos.flush();
    dos.close();

    conn.connect();

    int code = conn.getResponseCode();
    String message = conn.getResponseMessage();

    byte[] data = null;

    String encoding = conn.getContentEncoding();
    String error = null;

    if (code < 200 || code >= 300) {

        error = new String(toData(encoding, conn.getErrorStream()), "UTF-8");

        AQUtility.debug("error", error);
    } else {

        data = toData(encoding, conn.getInputStream());
    }

    AQUtility.debug("response", code);

    if (data != null) {
        AQUtility.debug(data.length, url);
    }

    status.code(code).message(message).redirect(url).time(new Date()).data(data).error(error).client(null);

}

From source file:com.canappi.connector.yp.yhere.CouponView.java

public ArrayList<Element> getCouponsByZip(HashMap<String, String> requestParameters) {

    ArrayList<Element> data = new ArrayList<Element>();

    System.setProperty("http.keepAlive", "false");
    System.setProperty("javax.net.debug", "all");
    // _FakeX509TrustManager.allowAllSSL();

    //Protocol::: HTTP GET
    StringBuffer query = new StringBuffer();

    HttpURLConnection connection = null;

    try {//w  ww  . jav a  2  s  .  com
        URL url;

        if (requestParameters != null) {
            String key;

            query.append(
                    "http://api2.yp.com/listings/v1/coupons?format=xml&key=5d0b448ba491c2dff5a36040a125df0a");
            query.append("&");
            key = "searchloc";
            String searchlocValue = requestParameters.get(key);
            String searchlocDefaultValue = retrieveFromUserDefaultsFor(key);
            if (searchlocValue.length() > 0) {
                query.append("" + key + "=" + requestParameters.get(key));
            } else {
                //try to find the value in the user defaults
                if (searchlocDefaultValue != null) {
                    query.append("" + key + "=" + retrieveFromUserDefaultsFor(key));
                }
            }

            url = new URL(query.toString());

        } else {

            url = new URL(
                    "http://api2.yp.com/listings/v1/coupons?format=xml&key=5d0b448ba491c2dff5a36040a125df0a");
        }

        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.setUseCaches(false);

        connection.setRequestMethod("GET");

        connection.setDoOutput(true);
        connection.setDoInput(true);

        connection.connect();

        int rc = connection.getResponseCode();
        Log.i("Response code", String.valueOf(rc));
        InputStream is;
        if (rc <= 400) {
            is = connection.getInputStream();
        } else {
            /* error from server */
            is = connection.getErrorStream();
        }

        //XML ResultSet

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource isrc = new InputSource();
            isrc.setByteStream(is);

            Document doc = db.parse(isrc);
            NodeList nodes = doc.getElementsByTagName("searchListings");

            if (nodes.getLength() > 0) {
                Element list = (Element) nodes.item(0);
                NodeList l = list.getChildNodes();
                for (int i = 0; i < l.getLength(); i++) {
                    Node n = l.item(i);
                    if (n.getNodeType() == Node.ELEMENT_NODE) {
                        Element row = (Element) l.item(i);
                        data.add(row);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    finally {
        connection.disconnect();
    }

    return data;

}

From source file:org.pixmob.httpclient.HttpRequestBuilder.java

public HttpResponse execute() throws HttpClientException {
    HttpURLConnection conn = null;
    UncloseableInputStream payloadStream = null;
    try {//from w  w  w .j  av a  2 s .c  om
        if (parameters != null && !parameters.isEmpty()) {
            final StringBuilder buf = new StringBuilder(256);
            if (HTTP_GET.equals(method) || HTTP_HEAD.equals(method)) {
                buf.append('?');
            }

            int paramIdx = 0;
            for (final Map.Entry<String, String> e : parameters.entrySet()) {
                if (paramIdx != 0) {
                    buf.append("&");
                }
                final String name = e.getKey();
                final String value = e.getValue();
                buf.append(URLEncoder.encode(name, CONTENT_CHARSET)).append("=")
                        .append(URLEncoder.encode(value, CONTENT_CHARSET));
                ++paramIdx;
            }

            if (!contentSet
                    && (HTTP_POST.equals(method) || HTTP_DELETE.equals(method) || HTTP_PUT.equals(method))) {
                try {
                    content = buf.toString().getBytes(CONTENT_CHARSET);
                } catch (UnsupportedEncodingException e) {
                    // Unlikely to happen.
                    throw new HttpClientException("Encoding error", e);
                }
            } else {
                uri += buf;
            }
        }

        conn = (HttpURLConnection) new URL(uri).openConnection();
        conn.setConnectTimeout(hc.getConnectTimeout());
        conn.setReadTimeout(hc.getReadTimeout());
        conn.setAllowUserInteraction(false);
        conn.setInstanceFollowRedirects(false);
        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setDoInput(true);

        if (headers != null && !headers.isEmpty()) {
            for (final Map.Entry<String, List<String>> e : headers.entrySet()) {
                final List<String> values = e.getValue();
                if (values != null) {
                    final String name = e.getKey();
                    for (final String value : values) {
                        conn.addRequestProperty(name, value);
                    }
                }
            }
        }

        if (cookies != null && !cookies.isEmpty()
                || hc.getInMemoryCookies() != null && !hc.getInMemoryCookies().isEmpty()) {
            final StringBuilder cookieHeaderValue = new StringBuilder(256);
            prepareCookieHeader(cookies, cookieHeaderValue);
            prepareCookieHeader(hc.getInMemoryCookies(), cookieHeaderValue);
            conn.setRequestProperty("Cookie", cookieHeaderValue.toString());
        }

        final String userAgent = hc.getUserAgent();
        if (userAgent != null) {
            conn.setRequestProperty("User-Agent", userAgent);
        }

        conn.setRequestProperty("Connection", "close");
        conn.setRequestProperty("Location", uri);
        conn.setRequestProperty("Referrer", uri);
        conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
        conn.setRequestProperty("Accept-Charset", CONTENT_CHARSET);

        if (conn instanceof HttpsURLConnection) {
            setupSecureConnection(hc.getContext(), (HttpsURLConnection) conn);
        }

        for (final HttpRequestHandler connHandler : reqHandlers) {
            try {
                connHandler.onRequest(conn);
            } catch (HttpClientException e) {
                throw e;
            } catch (Exception e) {
                throw new HttpClientException("Failed to prepare request to " + uri, e);
            }
        }

        // It seems that when writing content starts the connection
        if (HTTP_POST.equals(method) || HTTP_DELETE.equals(method) || HTTP_PUT.equals(method)) {

            if (content == null) {
                noContent();
            }

            conn.setDoOutput(true);
            if (!contentSet) {
                conn.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded; charset=" + CONTENT_CHARSET);
            } else if (contentType != null) {
                conn.setRequestProperty("Content-Type", contentType);
            }
            conn.setFixedLengthStreamingMode(content.length);

            final OutputStream out = conn.getOutputStream();
            out.write(content);
            out.flush();
        }

        conn.connect();

        final int statusCode = conn.getResponseCode();
        if (statusCode == -1) {
            throw new HttpClientException("Invalid response from " + uri);
        }
        if (!expectedStatusCodes.isEmpty() && !expectedStatusCodes.contains(statusCode)) {
            throw new HttpClientException(
                    "Expected status code " + expectedStatusCodes + ", got " + statusCode);
        } else if (expectedStatusCodes.isEmpty() && statusCode / 100 != 2) {
            throw new HttpClientException("Expected status code 2xx, got " + statusCode);
        }

        final Map<String, List<String>> headerFields = conn.getHeaderFields();
        final Map<String, String> inMemoryCookies = hc.getInMemoryCookies();
        if (headerFields != null) {
            final List<String> newCookies = headerFields.get("Set-Cookie");
            if (newCookies != null) {
                for (final String newCookie : newCookies) {
                    final String rawCookie = newCookie.split(";", 2)[0];
                    final int i = rawCookie.indexOf('=');
                    final String name = rawCookie.substring(0, i);
                    final String value = rawCookie.substring(i + 1);
                    inMemoryCookies.put(name, value);
                }
            }
        }

        if (isStatusCodeError(statusCode)) {
            // Got an error: cannot read input.
            payloadStream = new UncloseableInputStream(getErrorStream(conn));
        } else {
            payloadStream = new UncloseableInputStream(getInputStream(conn));
        }
        final HttpResponse resp = new HttpResponse(statusCode, payloadStream,
                headerFields == null ? NO_HEADERS : headerFields, inMemoryCookies);
        if (handler != null) {
            try {
                handler.onResponse(resp);
            } catch (HttpClientException e) {
                throw e;
            } catch (Exception e) {
                throw new HttpClientException("Error in response handler", e);
            }
        } else {
            final File temp = File.createTempFile("httpclient-req-", ".cache", hc.getContext().getCacheDir());
            resp.preload(temp);
            temp.delete();
        }
        return resp;
    } catch (SocketTimeoutException e) {
        if (handler != null) {
            try {
                handler.onTimeout();
                return null;
            } catch (HttpClientException e2) {
                throw e2;
            } catch (Exception e2) {
                throw new HttpClientException("Error in response handler", e2);
            }
        } else {
            throw new HttpClientException("Response timeout from " + uri, e);
        }
    } catch (IOException e) {
        throw new HttpClientException("Connection failed to " + uri, e);
    } finally {
        if (conn != null) {
            if (payloadStream != null) {
                // Fully read Http response:
                // http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html
                try {
                    while (payloadStream.read(buffer) != -1) {
                        ;
                    }
                } catch (IOException ignore) {
                }
                payloadStream.forceClose();
            }
            conn.disconnect();
        }
    }
}

From source file:com.cr_wd.android.network.HttpClient.java

/**
 * Performs a HTTP GET/POST Request//from   w  w w .j  a v  a  2s .  co  m
 * 
 * @return id of the request
 */
protected int doRequest(final Method method, final String url, HttpHeaders headers, HttpParams params,
        final HttpHandler handler) {
    if (headers == null) {
        headers = new HttpHeaders();
    }
    if (params == null) {
        params = new HttpParams();
    }

    handler.client = this;

    final int requestId = incrementRequestId();

    class HandlerRunnable extends Handler implements Runnable {

        private final Method method;
        private String url;
        private final HttpHeaders headers;
        private final HttpParams params;
        private final HttpHandler handler;
        private HttpResponse response;

        private boolean canceled = false;
        private int retries = 0;

        protected HandlerRunnable(final Method method, final String url, final HttpHeaders headers,
                final HttpParams params, final HttpHandler handler) {
            this.method = method;
            this.url = url;
            this.headers = headers;
            this.params = params;
            this.handler = handler;
        }

        @Override
        public void run() {
            execute();
        }

        private void execute() {
            response = new HttpResponse(requestId, method, url);

            HttpURLConnection conn = null;
            try {
                /* append query string for GET requests */
                if (method == Method.GET) {
                    if (!params.urlParams.isEmpty()) {
                        url += ('?' + params.getParamString());
                    }
                }

                /* setup headers for POST requests */
                if (method == Method.POST) {
                    headers.addHeader("Accept-Charset", requestOptions.encoding);
                    if (params.hasMultipartParams()) {
                        final SimpleMultipart multipart = params.getMultipart();
                        headers.addHeader("Content-Type", multipart.getContentType());
                    } else {
                        headers.addHeader("Content-Type",
                                "application/x-www-form-urlencoded;charset=" + requestOptions.encoding);
                    }
                }

                if (canceled) {
                    postCancel();
                    return;
                }

                /* open and configure the connection */
                conn = (HttpURLConnection) new URL(url).openConnection();

                postStart();

                if (method == Method.GET) {
                    conn = (HttpURLConnection) new URL(url).openConnection();
                    conn.setRequestMethod("GET");
                } else if (method == Method.POST) {
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setUseCaches(false);
                }
                conn.setAllowUserInteraction(false);
                conn.setReadTimeout(requestOptions.readTimeout);
                conn.setConnectTimeout(requestOptions.connectTimeout);

                /* add headers to the connection */
                for (final Map.Entry<String, List<String>> entry : headers.getHeaders().entrySet()) {
                    for (final String value : entry.getValue()) {
                        conn.addRequestProperty(entry.getKey(), value);
                    }
                }

                if (canceled) {
                    try {
                        conn.disconnect();
                    } catch (final Exception e) {
                    }
                    postCancel();
                    return;
                }

                response.requestProperties = conn.getRequestProperties();

                /* do post */
                if (method == Method.POST) {
                    InputStream is;

                    if (params.hasMultipartParams()) {
                        is = params.getMultipart().getContent();
                    } else {
                        is = new ByteArrayInputStream(params.getParamString().getBytes());
                    }

                    final OutputStream os = conn.getOutputStream();

                    writeStream(os, is);
                } else {
                    conn.connect();
                }

                if (canceled) {
                    try {
                        conn.disconnect();
                    } catch (final Exception e) {
                    }
                    postCancel();
                    return;
                }

                response.contentEncoding = conn.getContentEncoding();
                response.contentLength = conn.getContentLength();
                response.contentType = conn.getContentType();
                response.date = conn.getDate();
                response.expiration = conn.getExpiration();
                response.headerFields = conn.getHeaderFields();
                response.ifModifiedSince = conn.getIfModifiedSince();
                response.lastModified = conn.getLastModified();
                response.responseCode = conn.getResponseCode();
                response.responseMessage = conn.getResponseMessage();

                /* do get */
                if (conn.getResponseCode() < 400) {
                    response.responseBody = readStream(conn.getInputStream());
                    postSuccess();
                } else {
                    response.responseBody = readStream(conn.getErrorStream());
                    response.throwable = new Exception(response.responseMessage);
                    postError();
                }

            } catch (final Exception e) {
                if (retries < requestOptions.maxRetries) {
                    retries++;
                    postRetry();
                    execute();
                } else {
                    response.responseBody = e.getMessage();
                    response.throwable = e;
                    postError();
                }
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
        }

        private String readStream(final InputStream is) throws IOException {
            final BufferedInputStream bis = new BufferedInputStream(is);
            final ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int read = 0;
            final byte[] buffer = new byte[8192];
            while (true) {
                if (canceled) {
                    break;
                }

                read = bis.read(buffer);
                if (read == -1) {
                    break;
                }
                baf.append(buffer, 0, read);
            }

            try {
                bis.close();
            } catch (final IOException e) {
            }

            try {
                is.close();
            } catch (final IOException e) {
            }

            return new String(baf.toByteArray());
        }

        private void writeStream(final OutputStream os, final InputStream is) throws IOException {
            final BufferedInputStream bis = new BufferedInputStream(is);
            int read = 0;
            final byte[] buffer = new byte[8192];
            while (true) {
                if (canceled) {
                    break;
                }

                read = bis.read(buffer);
                if (read == -1) {
                    break;
                }
                os.write(buffer, 0, read);
            }

            if (!canceled) {
                os.flush();
            }

            try {
                os.close();
            } catch (final IOException e) {
            }

            try {
                bis.close();
            } catch (final IOException e) {
            }

            try {
                is.close();
            } catch (final IOException e) {
            }
        }

        @Override
        public void handleMessage(final Message msg) {
            if (msg.what == HttpHandler.MESSAGE_CANCEL) {
                canceled = true;
            }
        }

        private void postSuccess() {
            postMessage(HttpHandler.MESSAGE_SUCCESS);
        }

        private void postError() {
            postMessage(HttpHandler.MESSAGE_ERROR);
        }

        private void postCancel() {
            postMessage(HttpHandler.MESSAGE_CANCEL);
        }

        private void postStart() {
            postMessage(HttpHandler.MESSAGE_START);
        }

        private void postRetry() {
            postMessage(HttpHandler.MESSAGE_RETRY);
        }

        private void postMessage(final int what) {
            final Message msg = handler.obtainMessage();
            msg.what = what;
            msg.arg1 = requestId;
            msg.obj = response;
            handler.sendMessage(msg);
        }
    }
    ;
    /* Create a new HandlerRunnable and start it */
    final HandlerRunnable hr = new HandlerRunnable(method, url, headers, params, handler);
    requests.put(requestId, new WeakReference<Handler>(hr));
    new Thread(hr).start();

    /* Return with the request id */
    return requestId;
}

From source file:org.apache.cordova.core.FileTransfer.java

/**
 * Uploads the specified file to the server URL provided using an HTTP multipart request.
 * @param source        Full path of the file on the file system
 * @param target        URL of the server to receive the file
 * @param args          JSON Array of args
 * @param callbackContext    callback id for optional progress reports
 *
 * args[2] fileKey       Name of file request parameter
 * args[3] fileName      File name to be used on server
 * args[4] mimeType      Describes file content type
 * args[5] params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 *///from   w w w. java2  s .  co  m
private void upload(final String source, final String target, JSONArray args, CallbackContext callbackContext)
        throws JSONException {
    Log.d(LOG_TAG, "upload " + source + " to " + target);

    // Setup the options
    final String fileKey = getArgument(args, 2, "file");
    final String fileName = getArgument(args, 3, "image.jpg");
    final String mimeType = getArgument(args, 4, "image/jpeg");
    final JSONObject params = args.optJSONObject(5) == null ? new JSONObject() : args.optJSONObject(5);
    final boolean trustEveryone = args.optBoolean(6);
    // Always use chunked mode unless set to false as per API
    final boolean chunkedMode = args.optBoolean(7) || args.isNull(7);
    // Look for headers on the params map for backwards compatibility with older Cordova versions.
    final JSONObject headers = args.optJSONObject(8) == null ? params.optJSONObject("headers")
            : args.optJSONObject(8);
    final String objectId = args.getString(9);
    final String httpMethod = getArgument(args, 10, "POST");

    final CordovaResourceApi resourceApi = webView.getResourceApi();

    Log.d(LOG_TAG, "fileKey: " + fileKey);
    Log.d(LOG_TAG, "fileName: " + fileName);
    Log.d(LOG_TAG, "mimeType: " + mimeType);
    Log.d(LOG_TAG, "params: " + params);
    Log.d(LOG_TAG, "trustEveryone: " + trustEveryone);
    Log.d(LOG_TAG, "chunkedMode: " + chunkedMode);
    Log.d(LOG_TAG, "headers: " + headers);
    Log.d(LOG_TAG, "objectId: " + objectId);
    Log.d(LOG_TAG, "httpMethod: " + httpMethod);

    final Uri targetUri = resourceApi.remapUri(Uri.parse(target));
    // Accept a path or a URI for the source.
    Uri tmpSrc = Uri.parse(source);
    final Uri sourceUri = resourceApi
            .remapUri(tmpSrc.getScheme() != null ? tmpSrc : Uri.fromFile(new File(source)));

    int uriType = CordovaResourceApi.getUriType(targetUri);
    final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
    if (uriType != CordovaResourceApi.URI_TYPE_HTTP && !useHttps) {
        JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0);
        Log.e(LOG_TAG, "Unsupported URI: " + targetUri);
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
        return;
    }

    final RequestContext context = new RequestContext(source, target, callbackContext);
    synchronized (activeRequests) {
        activeRequests.put(objectId, context);
    }

    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            if (context.aborted) {
                return;
            }
            HttpURLConnection conn = null;
            HostnameVerifier oldHostnameVerifier = null;
            SSLSocketFactory oldSocketFactory = null;
            int totalBytes = 0;
            int fixedLength = -1;
            try {
                // Create return object
                FileUploadResult result = new FileUploadResult();
                FileProgressResult progress = new FileProgressResult();

                //------------------ CLIENT REQUEST
                // Open a HTTP connection to the URL based on protocol
                conn = resourceApi.createHttpConnection(targetUri);
                if (useHttps && trustEveryone) {
                    // Setup the HTTPS connection class to trust everyone
                    HttpsURLConnection https = (HttpsURLConnection) conn;
                    oldSocketFactory = trustAllHosts(https);
                    // Save the current hostnameVerifier
                    oldHostnameVerifier = https.getHostnameVerifier();
                    // Setup the connection not to verify hostnames
                    https.setHostnameVerifier(DO_NOT_VERIFY);
                }

                // Allow Inputs
                conn.setDoInput(true);

                // Allow Outputs
                conn.setDoOutput(true);

                // Don't use a cached copy.
                conn.setUseCaches(false);

                // Use a post method.
                conn.setRequestMethod(httpMethod);
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);

                // Set the cookies on the response
                String cookie = CookieManager.getInstance().getCookie(target);
                if (cookie != null) {
                    conn.setRequestProperty("Cookie", cookie);
                }

                // Handle the other headers
                if (headers != null) {
                    addHeadersToRequest(conn, headers);
                }

                /*
                * Store the non-file portions of the multipart data as a string, so that we can add it
                * to the contentSize, since it is part of the body of the HTTP request.
                */
                StringBuilder beforeData = new StringBuilder();
                try {
                    for (Iterator<?> iter = params.keys(); iter.hasNext();) {
                        Object key = iter.next();
                        if (!String.valueOf(key).equals("headers")) {
                            beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);
                            beforeData.append("Content-Disposition: form-data; name=\"").append(key.toString())
                                    .append('"');
                            beforeData.append(LINE_END).append(LINE_END);
                            beforeData.append(params.getString(key.toString()));
                            beforeData.append(LINE_END);
                        }
                    }
                } catch (JSONException e) {
                    Log.e(LOG_TAG, e.getMessage(), e);
                }

                beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);
                beforeData.append("Content-Disposition: form-data; name=\"").append(fileKey).append("\";");
                beforeData.append(" filename=\"").append(fileName).append('"').append(LINE_END);
                beforeData.append("Content-Type: ").append(mimeType).append(LINE_END).append(LINE_END);
                byte[] beforeDataBytes = beforeData.toString().getBytes("UTF-8");
                byte[] tailParamsBytes = (LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END)
                        .getBytes("UTF-8");

                // Get a input stream of the file on the phone
                OpenForReadResult readResult = resourceApi.openForRead(sourceUri);

                int stringLength = beforeDataBytes.length + tailParamsBytes.length;
                if (readResult.length >= 0) {
                    fixedLength = (int) readResult.length + stringLength;
                    progress.setLengthComputable(true);
                    progress.setTotal(fixedLength);
                }
                Log.d(LOG_TAG, "Content Length: " + fixedLength);
                // setFixedLengthStreamingMode causes and OutOfMemoryException on pre-Froyo devices.
                // http://code.google.com/p/android/issues/detail?id=3164
                // It also causes OOM if HTTPS is used, even on newer devices.
                boolean useChunkedMode = chunkedMode
                        && (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO || useHttps);
                useChunkedMode = useChunkedMode || (fixedLength == -1);

                if (useChunkedMode) {
                    conn.setChunkedStreamingMode(MAX_BUFFER_SIZE);
                    // Although setChunkedStreamingMode sets this header, setting it explicitly here works
                    // around an OutOfMemoryException when using https.
                    conn.setRequestProperty("Transfer-Encoding", "chunked");
                } else {
                    conn.setFixedLengthStreamingMode(fixedLength);
                }

                conn.connect();

                OutputStream sendStream = null;
                try {
                    sendStream = conn.getOutputStream();
                    synchronized (context) {
                        if (context.aborted) {
                            return;
                        }
                        context.currentOutputStream = sendStream;
                    }
                    //We don't want to change encoding, we just want this to write for all Unicode.
                    sendStream.write(beforeDataBytes);
                    totalBytes += beforeDataBytes.length;

                    // create a buffer of maximum size
                    int bytesAvailable = readResult.inputStream.available();
                    int bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
                    byte[] buffer = new byte[bufferSize];

                    // read file and write it into form...
                    int bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);

                    long prevBytesRead = 0;
                    while (bytesRead > 0) {
                        result.setBytesSent(totalBytes);
                        sendStream.write(buffer, 0, bytesRead);
                        totalBytes += bytesRead;
                        if (totalBytes > prevBytesRead + 102400) {
                            prevBytesRead = totalBytes;
                            Log.d(LOG_TAG, "Uploaded " + totalBytes + " of " + fixedLength + " bytes");
                        }
                        bytesAvailable = readResult.inputStream.available();
                        bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
                        bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);

                        // Send a progress event.
                        progress.setLoaded(totalBytes);
                        PluginResult progressResult = new PluginResult(PluginResult.Status.OK,
                                progress.toJSONObject());
                        progressResult.setKeepCallback(true);
                        context.sendPluginResult(progressResult);
                    }

                    // send multipart form data necessary after file data...
                    sendStream.write(tailParamsBytes);
                    totalBytes += tailParamsBytes.length;
                    sendStream.flush();
                } finally {
                    safeClose(readResult.inputStream);
                    safeClose(sendStream);
                }
                context.currentOutputStream = null;
                Log.d(LOG_TAG, "Sent " + totalBytes + " of " + fixedLength);

                //------------------ read the SERVER RESPONSE
                String responseString;
                int responseCode = conn.getResponseCode();
                Log.d(LOG_TAG, "response code: " + responseCode);
                Log.d(LOG_TAG, "response headers: " + conn.getHeaderFields());
                TrackingInputStream inStream = null;
                try {
                    inStream = getInputStream(conn);
                    synchronized (context) {
                        if (context.aborted) {
                            return;
                        }
                        context.currentInputStream = inStream;
                    }

                    ByteArrayOutputStream out = new ByteArrayOutputStream(
                            Math.max(1024, conn.getContentLength()));
                    byte[] buffer = new byte[1024];
                    int bytesRead = 0;
                    // write bytes to file
                    while ((bytesRead = inStream.read(buffer)) > 0) {
                        out.write(buffer, 0, bytesRead);
                    }
                    responseString = out.toString("UTF-8");
                } finally {
                    context.currentInputStream = null;
                    safeClose(inStream);
                }

                Log.d(LOG_TAG, "got response from server");
                Log.d(LOG_TAG, responseString.substring(0, Math.min(256, responseString.length())));

                // send request and retrieve response
                result.setResponseCode(responseCode);
                result.setResponse(responseString);

                context.sendPluginResult(new PluginResult(PluginResult.Status.OK, result.toJSONObject()));
            } catch (FileNotFoundException e) {
                JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn);
                Log.e(LOG_TAG, error.toString(), e);
                context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
            } catch (IOException e) {
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
                Log.e(LOG_TAG, error.toString(), e);
                Log.e(LOG_TAG, "Failed after uploading " + totalBytes + " of " + fixedLength + " bytes.");
                context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
                context.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
            } catch (Throwable t) {
                // Shouldn't happen, but will
                JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
                Log.e(LOG_TAG, error.toString(), t);
                context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
            } finally {
                synchronized (activeRequests) {
                    activeRequests.remove(objectId);
                }

                if (conn != null) {
                    // Revert back to the proper verifier and socket factories
                    // Revert back to the proper verifier and socket factories
                    if (trustEveryone && useHttps) {
                        HttpsURLConnection https = (HttpsURLConnection) conn;
                        https.setHostnameVerifier(oldHostnameVerifier);
                        https.setSSLSocketFactory(oldSocketFactory);
                    }
                }
            }
        }
    });
}

From source file:com.canappi.connector.yp.yhere.GameView.java

public ArrayList<Element> searchGamesByZip(HashMap<String, String> requestParameters) {

    ArrayList<Element> data = new ArrayList<Element>();

    System.setProperty("http.keepAlive", "false");
    System.setProperty("javax.net.debug", "all");
    // _FakeX509TrustManager.allowAllSSL();

    //Protocol::: HTTP GET
    StringBuffer query = new StringBuffer();

    HttpURLConnection connection = null;

    try {/*from w  w  w.  j  ava2s  .  c om*/
        URL url;

        if (requestParameters != null) {
            String key;

            query.append(
                    "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&term=games&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a");
            query.append("&");
            key = "searchloc";
            String searchlocValue = requestParameters.get(key);
            String searchlocDefaultValue = retrieveFromUserDefaultsFor(key);
            if (searchlocValue.length() > 0) {
                query.append("" + key + "=" + requestParameters.get(key));
            } else {
                //try to find the value in the user defaults
                if (searchlocDefaultValue != null) {
                    query.append("" + key + "=" + retrieveFromUserDefaultsFor(key));
                }
            }

            url = new URL(query.toString());

        } else {

            url = new URL(
                    "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&term=games&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a");
        }

        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.setUseCaches(false);

        connection.setRequestMethod("GET");

        connection.setDoOutput(true);
        connection.setDoInput(true);

        connection.connect();

        int rc = connection.getResponseCode();
        Log.i("Response code", String.valueOf(rc));
        InputStream is;
        if (rc <= 400) {
            is = connection.getInputStream();
        } else {
            /* error from server */
            is = connection.getErrorStream();
        }

        //XML ResultSet

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource isrc = new InputSource();
            isrc.setByteStream(is);

            Document doc = db.parse(isrc);
            NodeList nodes = doc.getElementsByTagName("searchListings");

            if (nodes.getLength() > 0) {
                Element list = (Element) nodes.item(0);
                NodeList l = list.getChildNodes();
                for (int i = 0; i < l.getLength(); i++) {
                    Node n = l.item(i);
                    if (n.getNodeType() == Node.ELEMENT_NODE) {
                        Element row = (Element) l.item(i);
                        data.add(row);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    finally {
        connection.disconnect();
    }

    return data;

}

From source file:com.canappi.connector.yp.yhere.BakeryView.java

public ArrayList<Element> searchBakeriesByZip(HashMap<String, String> requestParameters) {

    ArrayList<Element> data = new ArrayList<Element>();

    System.setProperty("http.keepAlive", "false");
    System.setProperty("javax.net.debug", "all");
    // _FakeX509TrustManager.allowAllSSL();

    //Protocol::: HTTP GET
    StringBuffer query = new StringBuffer();

    HttpURLConnection connection = null;

    try {/*from ww w.  ja  v  a2s .c o m*/
        URL url;

        if (requestParameters != null) {
            String key;

            query.append(
                    "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&term=bakery&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a");
            query.append("&");
            key = "searchloc";
            String searchlocValue = requestParameters.get(key);
            String searchlocDefaultValue = retrieveFromUserDefaultsFor(key);
            if (searchlocValue.length() > 0) {
                query.append("" + key + "=" + requestParameters.get(key));
            } else {
                //try to find the value in the user defaults
                if (searchlocDefaultValue != null) {
                    query.append("" + key + "=" + retrieveFromUserDefaultsFor(key));
                }
            }

            url = new URL(query.toString());

        } else {

            url = new URL(
                    "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&term=bakery&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a");
        }

        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.setUseCaches(false);

        connection.setRequestMethod("GET");

        connection.setDoOutput(true);
        connection.setDoInput(true);

        connection.connect();

        int rc = connection.getResponseCode();
        Log.i("Response code", String.valueOf(rc));
        InputStream is;
        if (rc <= 400) {
            is = connection.getInputStream();
        } else {
            /* error from server */
            is = connection.getErrorStream();
        }

        //XML ResultSet

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource isrc = new InputSource();
            isrc.setByteStream(is);

            Document doc = db.parse(isrc);
            NodeList nodes = doc.getElementsByTagName("searchListings");

            if (nodes.getLength() > 0) {
                Element list = (Element) nodes.item(0);
                NodeList l = list.getChildNodes();
                for (int i = 0; i < l.getLength(); i++) {
                    Node n = l.item(i);
                    if (n.getNodeType() == Node.ELEMENT_NODE) {
                        Element row = (Element) l.item(i);
                        data.add(row);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    finally {
        connection.disconnect();
    }

    return data;

}