Example usage for java.net HttpURLConnection getHeaderField

List of usage examples for java.net HttpURLConnection getHeaderField

Introduction

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

Prototype

public String getHeaderField(int n) 

Source Link

Document

Returns the value for the n th header field.

Usage

From source file:org.runnerup.export.FunBeatUploader.java

@Override
public Status upload(SQLiteDatabase db, long mID) {
    Status s;//  w  w w .  j  a va 2 s .co m
    if ((s = connect()) != Status.OK) {
        return s;
    }

    TCX tcx = new TCX(db);
    HttpURLConnection conn = null;
    Exception ex = null;
    try {
        StringWriter writer = new StringWriter();
        String id = tcx.export(mID, writer);
        conn = (HttpURLConnection) new URL(UPLOAD_URL).openConnection();
        conn.setInstanceFollowRedirects(false);
        addCookies(conn);
        getFormValues(conn); // execute the GET
        conn.disconnect();

        String viewKey = findName(formValues.keySet(), "VIEWSTATE");
        String eventKey = findName(formValues.keySet(), "EVENTVALIDATION");
        String fileKey = findName(formValues.keySet(), "FileUpload");
        String uploadKey = findName(formValues.keySet(), "UploadButton");

        Part<StringWritable> part1 = new Part<StringWritable>(viewKey,
                new StringWritable(formValues.get(viewKey)));

        Part<StringWritable> part2 = new Part<StringWritable>(eventKey,
                new StringWritable(formValues.get(eventKey)));

        Part<StringWritable> part3 = new Part<StringWritable>(fileKey, new StringWritable(writer.toString()));
        part3.contentType = "application/octet-stream";
        part3.filename = "jonas.tcx";

        Part<StringWritable> part4 = new Part<StringWritable>(uploadKey,
                new StringWritable(formValues.get(uploadKey)));
        Part<?> parts[] = { part1, part2, part3, part4 };

        conn = (HttpURLConnection) new URL(UPLOAD_URL).openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        addCookies(conn);
        postMulti(conn, parts);
        int responseCode = conn.getResponseCode();
        String amsg = conn.getResponseMessage();
        getCookies(conn);
        String redirect = null;
        if (responseCode == 302) {
            redirect = conn.getHeaderField("Location");
            conn.disconnect();
            conn = (HttpURLConnection) new URL(BASE_URL + redirect).openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod("GET");
            addCookies(conn);
            responseCode = conn.getResponseCode();
            amsg = conn.getResponseMessage();
            getCookies(conn);
        } else if (responseCode != 200) {
            System.err.println("FunBeatUploader::upload() - got " + responseCode + ", msg: " + amsg);
        }
        getFormValues(conn);
        conn.disconnect();

        viewKey = findName(formValues.keySet(), "VIEWSTATE");
        eventKey = findName(formValues.keySet(), "EVENTVALIDATION");
        String nextKey = findName(formValues.keySet(), "NextButton");
        String hidden = findName(formValues.keySet(), "ChoicesHiddenField");

        FormValues kv = new FormValues();
        kv.put(viewKey, formValues.get(viewKey));
        kv.put(eventKey, formValues.get(eventKey));
        kv.put(nextKey, "Nasta >>");
        kv.put(hidden, "[ \"import///" + id + "///tcx\" ]");

        String surl = BASE_URL + redirect;
        conn = (HttpURLConnection) new URL(surl).openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        addCookies(conn);
        {
            OutputStream wr = new BufferedOutputStream(conn.getOutputStream());
            kv.write(wr);
            wr.flush();
            wr.close();
            responseCode = conn.getResponseCode();
            amsg = conn.getResponseMessage();
            getCookies(conn);
            if (responseCode == 302) {
                redirect = conn.getHeaderField("Location");
                conn.disconnect();
                conn = (HttpURLConnection) new URL(BASE_URL + redirect).openConnection();
                conn.setInstanceFollowRedirects(false);
                conn.setRequestMethod("GET");
                addCookies(conn);
                responseCode = conn.getResponseCode();
                amsg = conn.getResponseMessage();
                getCookies(conn);
            }
            String html = getFormValues(conn);
            boolean ok = html.indexOf("r klar") > 0;
            System.err.println("ok: " + ok);

            conn.disconnect();
            if (ok) {
                return Uploader.Status.OK;
            } else {
                return Uploader.Status.CANCEL;
            }
        }
    } catch (IOException e) {
        ex = e;
    }

    s = Uploader.Status.ERROR;
    s.ex = ex;
    if (ex != null) {
        ex.printStackTrace();
    }
    return s;
}

From source file:at.spardat.xma.boot.transport.HTTPTransport.java

private Result getResourceImpl(IRtXMASessionClient session, URL url, long modifiedSince, String etag)
        throws CommunicationException {

    /* locals ---------------------------------- */
    Result result = new Result();
    int code = 0;
    HttpURLConnection conn;
    /* locals ---------------------------------- */

    try {//w w w.ja  va2  s .  c o  m
        conn = (HttpURLConnection) url.openConnection();
        if (conn instanceof HttpsURLConnection) {
            ((HttpsURLConnection) conn).setHostnameVerifier(hostnameVerifier);
        }
        sendCookies(session, url, conn);
        if (etag != null) {
            conn.setRequestProperty("If-None-Match", etag); //$NON-NLS-1$
        }

        String strUrl = url.toExternalForm();
        if (url.getQuery() == null && (strUrl.endsWith(".jar") || strUrl.endsWith(".xml"))) {
            conn.setRequestProperty(Statics.HTTP_CACHE_CONTROL, Statics.HTTP_MAX_AGE + "=0"); //$NON-NLS-1$
        }

        if (modifiedSince > 0) {
            // see sun bugid: 4397096
            // if HTTP_Util library is used, the original method may also be used.
            // conn.setIfModifiedSince(modifiedSince);
            conn.setRequestProperty(Statics.strIfModifiedSince, HTTPTransport.httpDate(modifiedSince));
        }
        conn.setRequestProperty(Statics.HTTP_ACCEPT, "*/*"); //$NON-NLS-1$
        conn.setRequestProperty(Statics.HTTP_USER_AGENT, Statics.HTTP_USER_AGENT_NAME);

    } catch (IOException exc) {
        log_.log(LogLevel.WARNING, "error loading '" + url.toString() + "' form server:", exc); //$NON-NLS-1$
        throw new ConnectException("error loading '" + url.toString() + "' form server:", exc);
    }

    try {
        code = conn.getResponseCode();
        if (code == HttpURLConnection.HTTP_NOT_MODIFIED) {
            result.contentLength_ = 0;
            result.lastModified_ = conn.getLastModified();
            if (result.lastModified_ <= 0) {
                result.lastModified_ = modifiedSince;
            }
            result.expirationDate_ = conn.getExpiration();
            result.etag_ = conn.getHeaderField(Statics.strEtag);
            if (result.etag_ == null) {
                result.etag_ = etag;
            }
            log_.log(LogLevel.FINE, "resource not modified: {0}", url.toExternalForm()); //$NON-NLS-1$
        } else if (code == HttpURLConnection.HTTP_OK) {
            result.contentLength_ = conn.getContentLength();
            result.lastModified_ = conn.getLastModified();
            result.expirationDate_ = conn.getExpiration();
            result.etag_ = conn.getHeaderField(Statics.strEtag);
            result.transformations_ = conn.getHeaderField(Statics.TRANSFORM_HEADER);

            result.setBuffer(this.readOutput(conn));

            if (result.contentLength_ < 0) {
                result.contentLength_ = result.buffer_.length;
            }
        } else if (code == HttpURLConnection.HTTP_MOVED_TEMP || code == HttpURLConnection.HTTP_MOVED_PERM) {
            String location = conn.getHeaderField(Statics.HTTP_LOCATION);
            throw new RedirectException("redirect received from " + url.toString() + " to " + location, code,
                    location);
        } else {
            if (code < 500)
                throw new ConnectException("error loading '" + url.toString() + "' from the server:", code);
            else
                throw new ServerException("error loading '" + url.toString() + "' from the server:", code);
        }
        readCookies(session, url, conn);
    } catch (RedirectException re) {
        throw re;
    } catch (CommunicationException ce) {
        if (code != 0)
            log_.log(LogLevel.WARNING, "http returncode: {0}", Integer.toString(code)); //$NON-NLS-1$
        log_.log(LogLevel.WARNING, "error loading '" + url.toString() + "' from the server:", ce); //$NON-NLS-1$
        throw ce;
    } catch (Exception ex) {
        if (code != 0)
            log_.log(LogLevel.WARNING, "http returncode: {0}", Integer.toString(code)); //$NON-NLS-1$
        log_.log(LogLevel.WARNING, "error loading '" + url.toString() + "' from the server:", ex); //$NON-NLS-1$
        if (code < 500)
            throw new ConnectException("error loading '" + url.toString() + "' from the server:", ex);
        else
            throw new ServerException("error loading '" + url.toString() + "' from the server:", ex);
    }

    return result;
}

From source file:org.runnerup.export.FunBeatSynchronizer.java

@Override
public Status upload(SQLiteDatabase db, long mID) {
    Status s;//from  www  .j ava 2 s  . c om
    if ((s = connect()) != Status.OK) {
        return s;
    }

    TCX tcx = new TCX(db);
    HttpURLConnection conn = null;
    Exception ex = null;
    try {
        StringWriter writer = new StringWriter();
        String id = tcx.export(mID, writer);
        conn = (HttpURLConnection) new URL(UPLOAD_URL).openConnection();
        conn.setInstanceFollowRedirects(false);
        addCookies(conn);
        getFormValues(conn); // execute the GET
        conn.disconnect();

        String viewKey = SyncHelper.findName(formValues.keySet(), "VIEWSTATE");
        String eventKey = SyncHelper.findName(formValues.keySet(), "EVENTVALIDATION");
        String fileKey = SyncHelper.findName(formValues.keySet(), "FileUpload");
        String uploadKey = SyncHelper.findName(formValues.keySet(), "UploadButton");

        Part<StringWritable> part1 = new Part<StringWritable>(viewKey,
                new StringWritable(formValues.get(viewKey)));

        Part<StringWritable> part2 = new Part<StringWritable>(eventKey,
                new StringWritable(formValues.get(eventKey)));

        Part<StringWritable> part3 = new Part<StringWritable>(fileKey, new StringWritable(writer.toString()));
        part3.setContentType("application/octet-stream");
        part3.setFilename("jonas.tcx");

        Part<StringWritable> part4 = new Part<StringWritable>(uploadKey,
                new StringWritable(formValues.get(uploadKey)));
        Part<?> parts[] = { part1, part2, part3, part4 };

        conn = (HttpURLConnection) new URL(UPLOAD_URL).openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.setDoOutput(true);
        conn.setRequestMethod(RequestMethod.POST.name());
        addCookies(conn);
        SyncHelper.postMulti(conn, parts);
        int responseCode = conn.getResponseCode();
        String amsg = conn.getResponseMessage();
        getCookies(conn);
        String redirect = null;
        if (responseCode == HttpStatus.SC_MOVED_TEMPORARILY) {
            redirect = conn.getHeaderField("Location");
            conn.disconnect();
            conn = (HttpURLConnection) new URL(BASE_URL + redirect).openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod(RequestMethod.GET.name());
            addCookies(conn);
            responseCode = conn.getResponseCode();
            amsg = conn.getResponseMessage();
            getCookies(conn);
        } else if (responseCode != HttpStatus.SC_OK) {
            Log.e(getName(), "FunBeatSynchronizer::upload() - got " + responseCode + ", msg: " + amsg);
        }
        getFormValues(conn);
        conn.disconnect();

        viewKey = SyncHelper.findName(formValues.keySet(), "VIEWSTATE");
        eventKey = SyncHelper.findName(formValues.keySet(), "EVENTVALIDATION");
        String nextKey = SyncHelper.findName(formValues.keySet(), "NextButton");
        String hidden = SyncHelper.findName(formValues.keySet(), "ChoicesHiddenField");

        FormValues kv = new FormValues();
        kv.put(viewKey, formValues.get(viewKey));
        kv.put(eventKey, formValues.get(eventKey));
        kv.put(nextKey, "Nasta >>");
        kv.put(hidden, "[ \"import///" + id + "///tcx\" ]");

        String surl = BASE_URL + redirect;
        conn = (HttpURLConnection) new URL(surl).openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.setDoOutput(true);
        conn.setRequestMethod(RequestMethod.POST.name());
        conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        addCookies(conn);
        {
            OutputStream wr = new BufferedOutputStream(conn.getOutputStream());
            kv.write(wr);
            wr.flush();
            wr.close();
            responseCode = conn.getResponseCode();
            amsg = conn.getResponseMessage();
            getCookies(conn);
            if (responseCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                redirect = conn.getHeaderField("Location");
                conn.disconnect();
                conn = (HttpURLConnection) new URL(BASE_URL + redirect).openConnection();
                conn.setInstanceFollowRedirects(false);
                conn.setRequestMethod(RequestMethod.GET.name());
                addCookies(conn);
                responseCode = conn.getResponseCode();
                amsg = conn.getResponseMessage();
                getCookies(conn);
            }
            String html = getFormValues(conn);
            boolean ok = html.indexOf("r klar") > 0;
            Log.e(getName(), "ok: " + ok);

            conn.disconnect();
            if (ok) {
                s = Status.OK;
                s.activityId = mID;
            } else {
                s = Status.CANCEL;
            }
            return s;
        }
    } catch (IOException e) {
        ex = e;
    }

    s = Synchronizer.Status.ERROR;
    s.ex = ex;
    if (ex != null) {
        ex.printStackTrace();
    }
    return s;
}

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

public boolean resumeImages(String msgSubject) {
    File file = null;/* ww w  .  j a  v a2 s.c  o  m*/
    long fileLength;

    try {

        String filename = "", num = "";

        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.connect();

        num = getNumber(msgSubject);
        filename = getTimestamp(msgSubject);

        file = new File(fileDir + "/" + getNumber(msgSubject) + "/Recieved", filename);
        if (!file.exists()) {
            file.createNewFile();
        }

        FileOutputStream fileOutput = new FileOutputStream(file);
        InputStream inputStream = connection.getInputStream();
        int totalSize = connection.getContentLength();
        Long downloadedSize = (long) 0;
        byte[] buffer = new byte[1024];
        int bufferLength = 0;
        while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
            downloadedSize += bufferLength;
            Log.i("Progress:", "downloadedSize:" + downloadedSize + "totalSize:" + totalSize);
        }
        fileOutput.close();
        Log.d("downloadedSize", downloadedSize + " @");
        if (downloadedSize == totalSize) {
            downloadedimageuri = file.getAbsolutePath();
            return true;
        }

        if (file.exists()) {
            connection.setAllowUserInteraction(true);
            connection.setRequestProperty("Range", "bytes=" + file.length() + "-");
        }

        connection.setConnectTimeout(14000);
        connection.setReadTimeout(20000);
        connection.connect();

        if (connection.getResponseCode() / 100 != 2)
            throw new Exception("Invalid response code!");
        else {
            String connectionField = connection.getHeaderField("content-range");

            if (connectionField != null) {
                String[] connectionRanges = connectionField.substring("bytes=".length()).split("-");
                downloadedSize = Long.valueOf(connectionRanges[0]);
            }

            if (connectionField == null && file.exists())
                file.delete();

            fileLength = connection.getContentLength() + downloadedSize;
            BufferedInputStream input = new BufferedInputStream(connection.getInputStream());
            RandomAccessFile output = new RandomAccessFile(file, "rw");
            output.seek(downloadedSize);

            byte data[] = new byte[1024];
            int count = 0;
            int __progress = 0;

            while ((count = input.read(data, 0, 1024)) != -1 && __progress != 100) {
                downloadedSize += count;
                output.write(data, 0, count);
                __progress = (int) ((downloadedSize * 100) / fileLength);
            }

            output.close();
            input.close();

        }

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

}

From source file:org.wso2.carbon.identity.authenticator.mobileconnect.MobileConnectAuthenticator.java

/**
 * Read the discovery API endpoint connections.
 *///from   w  w  w. j a v  a 2s  .c o  m
private void discoveryEndpointRead(AuthenticationContext context, HttpServletResponse response,
        HttpURLConnection connection) throws JSONException, AuthenticationFailedException {

    try {

        //get response from HttpURLConnection
        int responseCode = connection.getResponseCode();
        //if 200 OK
        if (responseCode == 200) {

            //read the response sent by the server
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            String responseString = stringBuilder.toString();
            reader.close();
            //create JSON object using the String retrieved
            JSONObject jsonObject = new JSONObject(responseString);
            //add the JSON object to the context of the session
            context.setProperty(MobileConnectAuthenticatorConstants.MOBILE_CONNECT_DISCOVERY_JSON_OBJECT,
                    jsonObject);
            //let the context know the end of the Discovery Process, and ste it to Authorization
            context.setProperty(MobileConnectAuthenticatorConstants.MOBILE_CONNECT_FLOW_STATUS,
                    MobileConnectAuthenticatorConstants.MOBILE_CONNECT_AUTHORIZATION_ENDPOINT);
            log.info("MSISDN is valid. Discovery Endpoint authorization successful");

        } else if (responseCode == 302) {
            //if 302, move temporarily
            String redirectUrl = connection.getHeaderField("location");
            //retrieve the redirect URL and redirect the flow
            response.sendRedirect(redirectUrl);
            context.setProperty(MobileConnectAuthenticatorConstants.MOBILE_CONNECT_FLOW_STATUS,
                    MobileConnectAuthenticatorConstants.MOBILE_CONNECT_AUTHORIZATION_ENDPOINT);
            log.info("MSISDN is invalid. Redirecting to mobile connect interface");

        } else if (responseCode == 401) {
            //if 401 unauthorized
            String retryURL = ConfigurationFacade.getInstance().getAuthenticationEndpointRetryURL();
            //redirect to retry URL
            response.sendRedirect(retryURL);
            log.error("No Authorization or Bad Session");

        } else if (responseCode == 404 || responseCode == 400) {
            //if 404, not found
            String retryURL = ConfigurationFacade.getInstance().getAuthenticationEndpointRetryURL();
            //redirect to retry URL
            response.sendRedirect(retryURL);
            log.error("Bad MSISDN is supplied");
        }

    } catch (IOException e) {
        throw new AuthenticationFailedException("response redirection failed", e);
    }

}

From source file:com.google.ytd.SubmitActivity.java

private String uploadMetaData(String filePath, boolean retry) throws IOException {
    String uploadUrl = INITIAL_UPLOAD_URL;

    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);
    urlConnection.setRequestMethod("POST");
    urlConnection.setDoOutput(true);/*from ww w .  j  a v a 2s  .  c  o m*/
    urlConnection.setRequestProperty("Content-Type", "application/atom+xml");
    urlConnection.setRequestProperty("Slug", filePath);
    String atomData;

    String title = getTitleText();
    String description = getDescriptionText();
    String category = DEFAULT_VIDEO_CATEGORY;
    this.tags = DEFAULT_VIDEO_TAGS;

    if (!Util.isNullOrEmpty(this.getTagsText())) {
        this.tags = this.getTagsText();
    }

    if (this.videoLocation == null) {
        String template = Util.readFile(this, R.raw.gdata).toString();
        atomData = String.format(template, title, description, category, this.tags);
    } else {
        String template = Util.readFile(this, R.raw.gdata_geo).toString();
        atomData = String.format(template, title, description, category, this.tags, videoLocation.getLatitude(),
                videoLocation.getLongitude());
    }

    OutputStreamWriter outStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());
    outStreamWriter.write(atomData);
    outStreamWriter.close();

    int responseCode = urlConnection.getResponseCode();
    if (responseCode < 200 || responseCode >= 300) {
        // The response code is 40X
        if ((responseCode + "").startsWith("4") && retry) {
            Log.d(LOG_TAG, "retrying to fetch auth token for " + youTubeName);
            this.clientLoginToken = authorizer.getFreshAuthToken(youTubeName, clientLoginToken);
            // Try again with fresh token
            return uploadMetaData(filePath, false);
        } else {
            throw new IOException(String.format("response code='%s' (code %d)" + " for %s",
                    urlConnection.getResponseMessage(), responseCode, urlConnection.getURL()));
        }
    }

    return urlConnection.getHeaderField("Location");
}

From source file:com.centurylink.mdw.util.HttpHelper.java

/**
 * Populates the response member.  Closes the connection.
 *///w w w . java  2s  .c om
private void readInput(HttpURLConnection connection) throws IOException {
    InputStream is = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        byte[] buffer = new byte[2048];
        try {
            is = connection.getInputStream();
            while (maxBytes == -1 || baos.size() < maxBytes) {
                int bytesRead = is.read(buffer);
                if (bytesRead == -1)
                    break;
                baos.write(buffer, 0, bytesRead);
            }
            response = baos.toByteArray();
            if (followHtmlHeadMetaRefresh && getResponse().indexOf("http-equiv") > 0) {
                try {
                    redirect = parseResponseForHtmlMetaEquiv(getResponse());
                    if (redirect != null)
                        response = new HttpHelper(this, redirect).getBytes();
                } catch (Exception ex) {
                    throw new IllegalArgumentException("Unparseable response: " + ex.getMessage(), ex);
                }

            }
        } catch (IOException ex) {
            InputStream eis = null;
            try {
                eis = connection.getErrorStream();
                while (maxBytes == -1 || baos.size() < maxBytes) {
                    int bytesRead = eis.read(buffer);
                    if (bytesRead == -1)
                        break;
                    baos.write(buffer, 0, bytesRead);
                }
                response = baos.toByteArray();
            } catch (Exception ex2) {
                // throw original exception
            } finally {
                if (eis != null) {
                    eis.close();
                }
            }
            throw ex;
        }
    } finally {
        if (is != null)
            is.close();
        connection.disconnect();
        responseCode = connection.getResponseCode();
        responseMessage = connection.getResponseMessage();
        headers = new HashMap<String, String>();
        for (String headerKey : connection.getHeaderFields().keySet()) {
            if (headerKey == null)
                headers.put("HTTP", connection.getHeaderField(headerKey));
            else
                headers.put(headerKey, connection.getHeaderField(headerKey));
        }
    }
}

From source file:org.eclipse.che.api.builder.internal.SourcesManagerImpl.java

private void download(String downloadUrl, java.io.File downloadTo) throws IOException {
    HttpURLConnection conn = null;
    try {//ww  w .j a v a 2  s . c  o m
        final LinkedList<java.io.File> q = new LinkedList<>();
        q.add(downloadTo);
        final long start = System.currentTimeMillis();
        final List<Pair<String, String>> md5sums = new LinkedList<>();
        while (!q.isEmpty()) {
            java.io.File current = q.pop();
            java.io.File[] list = current.listFiles();
            if (list != null) {
                for (java.io.File f : list) {
                    if (f.isDirectory()) {
                        q.push(f);
                    } else {
                        md5sums.add(Pair.of(com.google.common.io.Files.hash(f, Hashing.md5()).toString(),
                                downloadTo.toPath().relativize(f.toPath()).toString().replace("\\", "/"))); //Replacing of "\" is need for windows support
                    }
                }
            }
        }
        final long end = System.currentTimeMillis();
        if (md5sums.size() > 0) {
            LOG.debug("count md5sums of {} files, time: {}ms", md5sums.size(), (end - start));
        }
        conn = (HttpURLConnection) new URL(downloadUrl).openConnection();
        conn.setConnectTimeout(CONNECT_TIMEOUT);
        conn.setReadTimeout(READ_TIMEOUT);
        final EnvironmentContext context = EnvironmentContext.getCurrent();
        if (context.getUser() != null && context.getUser().getToken() != null) {
            conn.setRequestProperty(HttpHeaders.AUTHORIZATION, context.getUser().getToken());
        }
        if (!md5sums.isEmpty()) {
            conn.setRequestMethod(HttpMethod.POST);
            conn.setRequestProperty("Content-type", MediaType.TEXT_PLAIN);
            conn.setRequestProperty(HttpHeaders.ACCEPT, MediaType.MULTIPART_FORM_DATA);
            conn.setDoOutput(true);
            try (OutputStream output = conn.getOutputStream(); Writer writer = new OutputStreamWriter(output)) {
                for (Pair<String, String> pair : md5sums) {
                    writer.write(pair.first);
                    writer.write(' ');
                    writer.write(pair.second);
                    writer.write('\n');
                }
            }
        }
        final int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentType = conn.getHeaderField("content-type");
            if (contentType.startsWith(MediaType.MULTIPART_FORM_DATA)) {
                final HeaderParameterParser headerParameterParser = new HeaderParameterParser();
                final String boundary = headerParameterParser.parse(contentType).get("boundary");
                try (InputStream in = conn.getInputStream()) {
                    MultipartStream multipart = new MultipartStream(in, boundary.getBytes());
                    boolean hasMore = multipart.skipPreamble();
                    while (hasMore) {
                        final Map<String, List<String>> headers = parseChunkHeader(
                                CharStreams.readLines(new StringReader(multipart.readHeaders())));
                        final List<String> contentDisposition = headers.get("content-disposition");
                        final String name = headerParameterParser.parse(contentDisposition.get(0)).get("name");
                        if ("updates".equals(name)) {
                            int length = -1;
                            List<String> contentLengthHeader = headers.get("content-length");
                            if (contentLengthHeader != null && !contentLengthHeader.isEmpty()) {
                                length = Integer.parseInt(contentLengthHeader.get(0));
                            }
                            if (length < 0 || length > 204800) {
                                java.io.File tmp = java.io.File.createTempFile("tmp", ".zip", directory);
                                try {
                                    try (FileOutputStream fOut = new FileOutputStream(tmp)) {
                                        multipart.readBodyData(fOut);
                                    }
                                    ZipUtils.unzip(tmp, downloadTo);
                                } finally {
                                    if (tmp.exists()) {
                                        tmp.delete();
                                    }
                                }
                            } else {
                                final ByteArrayOutputStream bOut = new ByteArrayOutputStream(length);
                                multipart.readBodyData(bOut);
                                ZipUtils.unzip(new ByteArrayInputStream(bOut.toByteArray()), downloadTo);
                            }
                        } else if ("removed-paths".equals(name)) {
                            final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
                            multipart.readBodyData(bOut);
                            final String[] removed = JsonHelper.fromJson(
                                    new ByteArrayInputStream(bOut.toByteArray()), String[].class, null);
                            for (String path : removed) {
                                java.io.File f = new java.io.File(downloadTo, path);
                                if (!f.delete()) {
                                    throw new IOException(String.format("Unable delete %s", path));
                                }
                            }
                        } else {
                            // To /dev/null :)
                            multipart.readBodyData(DEV_NULL);
                        }
                        hasMore = multipart.readBoundary();
                    }
                }
            } else {
                try (InputStream in = conn.getInputStream()) {
                    ZipUtils.unzip(in, downloadTo);
                }
            }
        } else if (responseCode != HttpURLConnection.HTTP_NO_CONTENT) {
            throw new IOException(
                    String.format("Invalid response status %d from remote server. ", responseCode));
        }
    } catch (ParseException | JsonParseException e) {
        throw new IOException(e.getMessage(), e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}