Example usage for java.net HttpURLConnection getErrorStream

List of usage examples for java.net HttpURLConnection getErrorStream

Introduction

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

Prototype

public InputStream getErrorStream() 

Source Link

Document

Returns the error stream if the connection failed but the server sent useful data nonetheless.

Usage

From source file:com.facebook.android.FBUtil.java

/**
 * Connect to an HTTP URL and return the response as a string.
 *
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 *
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String// www  .  j a  v  a 2  s  .co  m
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    // Try to get filename key
    String filename = params.getString("filename");

    // If found
    if (filename != null) {
        // Remove from params
        params.remove("filename");
    }

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Facebook-FBUtil", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + ((filename) != null ? filename : key)
                        + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:com.luke.lukef.lukeapp.tools.LukeNetUtils.java

/**
 * Generic post method for the luke api.
 * @param urlString Url to send the request to
 * @param params Parameters to send with the request as a String
 * @return boolean indicating the success of the request
 *///w  ww  . ja  va 2s  .c o m
private boolean postMethod(String urlString, String params) {
    try {
        HttpURLConnection conn;
        URL url = new URL(urlString);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty(context.getString(R.string.authorization),
                context.getString(R.string.bearer) + SessionSingleton.getInstance().getIdToken());
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("charset", "utf-8");
        conn.setDoOutput(true);

        //get the output stream of the connection
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        //write the JSONobject to the connections output
        writer.write(params);

        //flush and close the writer
        writer.flush();
        writer.close();

        //get the response, if successfull, get inputstream, if unsuccessful get errorStream
        BufferedReader bufferedReader;
        Log.e(TAG, "updateUserImage call: RESPONSE CODE:" + conn.getResponseCode());
        if (conn.getResponseCode() != 200) {
            bufferedReader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));

        } else {
            // TODO: 25/11/2016 check for authorization error, respond accordingly
            bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        }
        String jsonString;
        StringBuilder stringBuilder = new StringBuilder();
        String line2;
        while ((line2 = bufferedReader.readLine()) != null) {
            stringBuilder.append(line2).append("\n");
        }
        bufferedReader.close();
        jsonString = stringBuilder.toString();
        Log.e(TAG, "updateUserImage run: Result : " + jsonString);
        conn.disconnect();
        return true;
    } catch (IOException e) {
        Log.e(TAG, "postMethod: ", e);
        return false;
    }
}

From source file:com.wareninja.android.opensource.oauth2login.common.Utils.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * //w  w  w.  j  a v a  2  s.  c o m
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 * 
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    if (AppContext.DEBUG)
        Log.d("Facebook-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {

            /*
             if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
             }
             */
            // YG: added this to avoid fups
            byte[] byteArr = null;
            try {
                byteArr = (byte[]) params.get(key);
            } catch (Exception ex1) {
            }
            if (byteArr != null)
                dataparams.putByteArray(key, byteArr);
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    if (AppContext.DEBUG)
        Log.d("Facebook-Util", method + " response: " + response);

    return response;
}

From source file:org.apache.ambari.server.controller.metrics.timeline.MetricsRequestHelperTest.java

@Test
public void testFetchTimelineMetrics() throws Exception {

    EasyMockSupport easyMockSupport = new EasyMockSupport();
    final long now = System.currentTimeMillis();
    TimelineMetrics metrics = new TimelineMetrics();
    TimelineMetric timelineMetric = new TimelineMetric();
    timelineMetric.setMetricName("cpu_user");
    timelineMetric.setAppId("app1");
    TreeMap<Long, Double> metricValues = new TreeMap<Long, Double>();
    metricValues.put(now + 100, 1.0);/* w  w  w. ja  v  a2  s  . com*/
    metricValues.put(now + 200, 2.0);
    metricValues.put(now + 300, 3.0);
    timelineMetric.setMetricValues(metricValues);
    metrics.getMetrics().add(timelineMetric);

    ObjectMapper mapper = new ObjectMapper();
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
    mapper.setAnnotationIntrospector(introspector);
    ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
    String metricsResponse = writer.writeValueAsString(metrics);

    InputStream inputStream = IOUtils.toInputStream(metricsResponse);
    HttpURLConnection httpURLConnectionMock = createMock(HttpURLConnection.class);
    expect(httpURLConnectionMock.getInputStream()).andReturn(inputStream).once();
    expect(httpURLConnectionMock.getResponseCode()).andReturn(HttpStatus.SC_OK).once();

    URLStreamProvider urlStreamProviderMock = createMock(URLStreamProvider.class);
    expect(urlStreamProviderMock.processURL(EasyMock.isA(String.class), EasyMock.isA(String.class),
            isNull(String.class), EasyMock.isA(Map.class))).andReturn(httpURLConnectionMock).once();

    replay(httpURLConnectionMock, urlStreamProviderMock);

    //Case 1 : No error.
    String randomSpec = "http://localhost:6188/ws/v1/timeline/metrics?metricNames=cpu_wio&hostname=host1&appId=HOST"
            + "&startTime=1447912834&endTime=1447990034&precision=SECONDS";
    MetricsRequestHelper metricsRequestHelper = new MetricsRequestHelper(urlStreamProviderMock);
    metricsRequestHelper.fetchTimelineMetrics(new URIBuilder(randomSpec), now, now + 300);

    easyMockSupport.verifyAll();

    //Case 2 : Precision Error returned first time.
    String metricsPrecisionErrorResponse = "{\"exception\": \"PrecisionLimitExceededException\",\n"
            + "\"message\": \"Requested precision (SECONDS) for given time range causes result set size of 169840, "
            + "which exceeds the limit - 15840. Please request higher precision.\",\n"
            + "\"javaClassName\": \"org.apache.hadoop.metrics2.sink.timeline.PrecisionLimitExceededException\"\n"
            + "}";

    InputStream errorStream = IOUtils.toInputStream(metricsPrecisionErrorResponse);
    inputStream = IOUtils.toInputStream(metricsResponse); //Reloading stream.

    httpURLConnectionMock = createMock(HttpURLConnection.class);
    expect(httpURLConnectionMock.getErrorStream()).andReturn(errorStream).once();
    expect(httpURLConnectionMock.getInputStream()).andReturn(inputStream).once();
    expect(httpURLConnectionMock.getResponseCode()).andReturn(HttpStatus.SC_BAD_REQUEST).once()
            .andReturn(HttpStatus.SC_OK).once();

    urlStreamProviderMock = createMock(URLStreamProvider.class);
    expect(urlStreamProviderMock.processURL(EasyMock.isA(String.class), EasyMock.isA(String.class),
            isNull(String.class), EasyMock.isA(Map.class))).andReturn(httpURLConnectionMock).times(2);

    replay(httpURLConnectionMock, urlStreamProviderMock);

    metricsRequestHelper = new MetricsRequestHelper(urlStreamProviderMock);
    metricsRequestHelper.fetchTimelineMetrics(new URIBuilder(randomSpec), now, now + 300);

    easyMockSupport.verifyAll();

}

From source file:ca.weblite.contacts.webservice.RESTService.java

private boolean sendPush(String[] deviceIds, String message, String type) throws IOException {
    StringBuilder sb = new StringBuilder();
    for (String did : deviceIds) {
        sb.append("&device=").append(did);
    }/*from w w w  .  ja  va2s  .c  o m*/
    String device = sb.toString();
    HttpURLConnection connection = (HttpURLConnection) new URL("https://push.codenameone.com/push/push")
            .openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

    //String device = "&device=6430232162074624&device=6095332624039936";

    String query = "token=" + RESTServiceConfiguration.getPushToken() + device + "&type=" + type + "&auth="
            + RESTServiceConfiguration.getGcmApiKey() + "&certPassword="
            + RESTServiceConfiguration.getIOSPushCertPassword() + "&cert="
            + RESTServiceConfiguration.getIOSPushCertURL() + "&body=" + URLEncoder.encode(message, "UTF-8")
            + "&production=false";

    System.out.println("Query is " + query);
    try (OutputStream output = connection.getOutputStream()) {
        output.write(query.getBytes("UTF-8"));
    }
    //        catch (IOException ex) {
    //            Logger.getLogger(RESTService.class.getName()).log(Level.SEVERE, null, ex);
    //        }

    int responseCode = connection.getResponseCode();
    System.out.println("Push response code " + responseCode);
    switch (responseCode) {
    case 200:
    case 201: {
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        System.out.println(sb.toString());
        break;
    }
    default: {

        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        System.out.println(sb.toString());

        return false;
    }

    }

    return true;
}

From source file:com.snaplogic.snaps.lunex.RequestProcessor.java

public String execute(RequestBuilder rBuilder) throws MalformedURLException, IOException {
    try {/*www .j a v  a2s .  c o m*/
        URL api_url = new URL(rBuilder.getURL());
        HttpURLConnection httpUrlConnection = (HttpURLConnection) api_url.openConnection();
        httpUrlConnection.setRequestMethod(rBuilder.getMethod().toString());
        httpUrlConnection.setDoInput(true);
        httpUrlConnection.setDoOutput(true);
        if (rBuilder.getSnapType() != LunexSnaps.Read) {
            rBuilder.getHeaders().add(Pair.of(CONTENT_LENGTH, rBuilder.getRequestBodyLenght()));
        }
        for (Pair<String, String> header : rBuilder.getHeaders()) {
            if (!StringUtils.isEmpty(header.getKey()) && !StringUtils.isEmpty(header.getValue())) {
                httpUrlConnection.setRequestProperty(header.getKey(), header.getValue());
            }
        }
        log.debug(String.format(LUNEX_HTTP_INFO, rBuilder.getSnapType(), rBuilder.getURL(),
                httpUrlConnection.getRequestProperties().toString()));
        if (rBuilder.getSnapType() != LunexSnaps.Read) {
            String paramsJson = null;
            if (!StringUtils.isEmpty(paramsJson = rBuilder.getRequestBody())) {
                DataOutputStream cgiInput = new DataOutputStream(httpUrlConnection.getOutputStream());
                log.debug(String.format(LUNEX_HTTP_REQ_INFO, paramsJson));
                cgiInput.writeBytes(paramsJson);
                cgiInput.flush();
                IOUtils.closeQuietly(cgiInput);
            }
        }

        List<String> input = null;
        StringBuilder response = new StringBuilder();
        try (InputStream iStream = httpUrlConnection.getInputStream()) {
            input = IOUtils.readLines(iStream);
        } catch (IOException ioe) {
            log.warn(String.format(INPUT_STREAM_ERROR, ioe.getMessage()));
            try (InputStream eStream = httpUrlConnection.getErrorStream()) {
                if (eStream != null) {
                    input = IOUtils.readLines(eStream);
                } else {
                    response.append(String.format(INPUT_STREAM_ERROR, ioe.getMessage()));
                }
            } catch (IOException ioe1) {
                log.warn(String.format(INPUT_STREAM_ERROR, ioe1.getMessage()));
            }
        }
        statusCode = httpUrlConnection.getResponseCode();
        log.debug(String.format(HTTP_STATUS, statusCode));
        if (input != null && !input.isEmpty()) {
            for (String line : input) {
                response.append(line);
            }
        }
        return formatResponse(response, rBuilder);
    } catch (MalformedURLException me) {
        log.error(me.getMessage(), me);
        throw me;
    } catch (IOException ioe) {
        log.error(ioe.getMessage(), ioe);
        throw ioe;
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
        throw ex;
    }
}

From source file:org.jmxtrans.embedded.output.StackdriverWriter.java

/**
 * Send given metrics to the Stackdriver server using HTTP
 * /*from   www .java 2  s  . co m*/
 * @param results
 *            Iterable collection of data points
 */
@Override
public void write(Iterable<QueryResult> results) {
    logger.debug("Export to '{}', proxy {} metrics {}", url, proxy, results);

    HttpURLConnection urlConnection = null;

    try {
        if (proxy == null) {
            urlConnection = (HttpURLConnection) url.openConnection();
        } else {
            urlConnection = (HttpURLConnection) url.openConnection(proxy);
        }
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setReadTimeout(stackdriverApiTimeoutInMillis);
        urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8");
        urlConnection.setRequestProperty("x-stackdriver-apikey", apiKey);

        serialize(results, urlConnection.getOutputStream());
        int responseCode = urlConnection.getResponseCode();
        if (responseCode != 200 && responseCode != 201) {
            exceptionCounter.incrementAndGet();
            logger.warn("Failure {}:'{}' to send result to Stackdriver server '{}' with proxy {}", responseCode,
                    urlConnection.getResponseMessage(), url, proxy);
        }
        if (logger.isTraceEnabled()) {
            IoUtils2.copy(urlConnection.getInputStream(), System.out);
        }
    } catch (Exception e) {
        exceptionCounter.incrementAndGet();
        logger.warn("Failure to send result to Stackdriver server '{}' with proxy {}", url, proxy, e);
    } finally {
        if (urlConnection != null) {
            try {
                InputStream in = urlConnection.getInputStream();
                IoUtils2.copy(in, IoUtils2.nullOutputStream());
                IoUtils2.closeQuietly(in);
                InputStream err = urlConnection.getErrorStream();
                if (err != null) {
                    IoUtils2.copy(err, IoUtils2.nullOutputStream());
                    IoUtils2.closeQuietly(err);
                }
                urlConnection.disconnect();
            } catch (IOException e) {
                logger.warn("Error flushing http connection for one result, continuing");
                logger.debug("Stack trace for the http connection, usually a network timeout", e);
            }
        }

    }
}

From source file:api.wireless.gdata.client.TokenFactory.java

/**
 * Makes a HTTP POST request to the provided {@code url} given the
 * provided {@code parameters}.  It returns the output from the POST
 * handler as a String object./*from   w  w  w  .  ja v a2 s.com*/
 *
 * @param url the URL to post the request
 * @param parameters the parameters to post to the handler
 * @return the output from the handler
 * @throws IOException if an I/O exception occurs while creating, writing,
 *                     or reading the request
 */
public String makePostRequest(URL url, Map<String, String> parameters) throws IOException {

    // Open connection      
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    // Set properties of the connection
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches(false);
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // Form the POST parameters
    StringBuilder content = new StringBuilder();
    boolean first = true;
    for (Map.Entry<String, String> parameter : parameters.entrySet()) {
        if (!first) {
            content.append("&");
        }
        content.append(CharEscapers.uriEscaper().escape(parameter.getKey())).append("=");
        content.append(CharEscapers.uriEscaper().escape(parameter.getValue()));
        first = false;
    }

    OutputStream outputStream = null;
    try {
        outputStream = urlConnection.getOutputStream();
        outputStream.write(content.toString().getBytes("utf-8"));
        outputStream.flush();
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }

    // Retrieve the output
    InputStream inputStream = null;
    StringBuilder outputBuilder = new StringBuilder();
    try {
        int responseCode = urlConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            inputStream = urlConnection.getInputStream();
        } else {
            inputStream = urlConnection.getErrorStream();
        }

        String string;
        if (inputStream != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            while (null != (string = reader.readLine())) {
                outputBuilder.append(string).append('\n');
            }
        }
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
    return outputBuilder.toString();
}

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

public ServiceRecord addServiceRecord(TempServiceRecord serviceRecord) throws IOException, JSONException {
    URL requestURL = new URL(serviceURL + "add");
    HttpURLConnection connection = (HttpURLConnection) requestURL.openConnection();
    connection.setDoInput(true);//from w w w  . j a  va 2 s.c  o m
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("charset", "utf-8");
    String urlParameters = "";
    urlParameters += "key=" + Globals.access_key;
    urlParameters += "&vehicle-id=" + serviceRecord.getParentVehicle().getId();
    urlParameters += "&type-id=" + serviceRecord.getType().getValue();
    urlParameters += "&service-desc=" + serviceRecord.getDescription();
    urlParameters += "&service-date=" + serviceRecord.getServiceDate().getMillis() / 1000L;
    urlParameters += "&service-mileage=" + serviceRecord.getMileage();
    connection.setRequestProperty("Content-Length", "" + urlParameters.getBytes().length);
    connection.setUseCaches(false);
    OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    writer.write(urlParameters);
    writer.flush();
    writer.close();

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

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

        JSONObject json = new JSONObject(response.toString());
        return new Deserializer().deserializeService(json, response.toString());
    } else if (responseCode == 400) {
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        throw new IOException(response.toString());
    } else {
        throw new IOException("Got response code: " + responseCode);
    }
}

From source file:io.github.retz.web.Client.java

public int getBinaryFile(int id, String file, OutputStream out) throws IOException {
    String date = TimestampHelper.now();
    String resource = "/job/" + id + "/download?path=" + file;
    AuthHeader header = authenticator.header("GET", "", date, resource);
    URL url = new URL(uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + resource); // TODO url-encode!
    LOG.info("Fetching {}", url);
    HttpURLConnection conn;

    conn = (HttpURLConnection) url.openConnection();
    //LOG.info("classname> {}", conn.getClass().getName());
    if (uri.getScheme().equals("https") && !checkCert && conn instanceof HttpsURLConnection) {
        if (verboseLog) {
            LOG.warn(//from w  ww  .  j a v a 2 s . com
                    "DANGER ZONE: TLS certificate check is disabled. Set 'retz.tls.insecure = false' at config file to supress this message.");
        }
        HttpsURLConnection sslCon = (HttpsURLConnection) conn;
        if (socketFactory != null) {
            sslCon.setSSLSocketFactory(socketFactory);
        }
        if (hostnameVerifier != null) {
            sslCon.setHostnameVerifier(hostnameVerifier);
        }
    }
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "application/octet-stream");
    conn.setRequestProperty("Authorization", header.buildHeader());
    conn.setRequestProperty("Date", date);
    conn.setRequestProperty("Content-md5", "");
    conn.setDoInput(true);
    String s2s = authenticator.string2sign("GET", "", date, resource);
    LOG.debug("Authorization: {} / S2S={}", header.buildHeader(), s2s);

    if (conn.getResponseCode() != 200) {
        if (verboseLog) {
            LOG.warn("HTTP Response:", conn.getResponseMessage());
        }
        if (conn.getResponseCode() < 200) {
            throw new AssertionError(conn.getResponseMessage());
        } else if (conn.getResponseCode() == 404) {
            throw new FileNotFoundException(url.toString());
        } else {
            String message;
            try {
                Response response = MAPPER.readValue(conn.getErrorStream(), Response.class);
                message = response.status();
                LOG.error(message, response);
            } catch (JsonProcessingException e) {
                message = e.toString();
                LOG.error(message, e);
            }
            throw new UnknownError(message);
        }
    }

    int size = conn.getContentLength();
    if (size < 0) {
        throw new IOException("Illegal content length:" + size);
    } else if (size == 0) {
        // not bytes to save;
        return 0;
    }
    try {
        return IOUtils.copy(conn.getInputStream(), out);
    } finally {
        conn.disconnect();
    }
}