Example usage for java.net HttpURLConnection getIfModifiedSince

List of usage examples for java.net HttpURLConnection getIfModifiedSince

Introduction

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

Prototype

public long getIfModifiedSince() 

Source Link

Document

Returns the value of this object's ifModifiedSince field.

Usage

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

/**
 * Performs a HTTP GET/POST Request//from  w  ww  .j  a  v  a  2  s. c o 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;
}