com.cloudbees.clickstack.util.HttpUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.cloudbees.clickstack.util.HttpUtils.java

Source

/*
 * Copyright 2010-2013, CloudBees Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.cloudbees.clickstack.util;

import com.cloudbees.clickstack.util.exception.RuntimeIOException;
import com.google.common.base.Preconditions;
import com.google.common.io.ByteStreams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * HTTP Utils.
 *
 * @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
 */
public class HttpUtils {
    protected static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * Save the content of the given {@code url} to the given {@code destFile}.
     *
     * @param url
     * @param destFile
     * @throws RuntimeIOException
     */
    public static void get(@Nonnull URL url, @Nonnull Path destFile) throws RuntimeIOException {
        try {
            HttpURLConnection cnn = (HttpURLConnection) url.openConnection();
            int responseCode = cnn.getResponseCode();
            Preconditions.checkState(responseCode == HttpURLConnection.HTTP_OK,
                    "Unexpected response code {}for {}", responseCode, url);
            InputStream in = cnn.getInputStream();
            OutputStream out = Files.newOutputStream(destFile);
            long length = ByteStreams.copy(in, out);
            logger.debug("Copied {} in {}: {}bytes", url, destFile, length);
        } catch (IOException e) {
            throw new RuntimeIOException("Exception downloading the content of '" + url + "' to '" + destFile + "'",
                    e);
        }
    }
}