Example usage for org.apache.http.client.methods HttpUriRequest getRequestLine

List of usage examples for org.apache.http.client.methods HttpUriRequest getRequestLine

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpUriRequest getRequestLine.

Prototype

RequestLine getRequestLine();

Source Link

Usage

From source file:org.dasein.cloud.azure.AzureMethod.java

public @Nullable Document getAsXML(@Nonnull String account, @Nonnull URI uri)
        throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("enter - " + AzureMethod.class.getName() + ".get(" + account + "," + uri + ")");
    }/*from w  w  w  . ja  va 2 s.  c  o m*/
    if (wire.isDebugEnabled()) {
        wire.debug("--------------------------------------------------------> " + uri.toASCIIString());
        wire.debug("");
    }
    try {
        HttpClient client = getClient();
        HttpUriRequest get = new HttpGet(uri);

        //get.addHeader("Content-Type", "application/xml");
        if (uri.toString().indexOf("/services/images") > -1) {
            get.addHeader("x-ms-version", "2012-08-01");
        } else {
            get.addHeader("x-ms-version", "2012-03-01");
        }
        if (wire.isDebugEnabled()) {
            wire.debug(get.getRequestLine().toString());
            for (Header header : get.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
        }
        HttpResponse response;
        StatusLine status;

        try {
            response = client.execute(get);
            status = response.getStatusLine();
        } catch (IOException e) {
            logger.error("get(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
            if (logger.isTraceEnabled()) {
                e.printStackTrace();
            }
            throw new CloudException(e);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("get(): HTTP Status " + status);
        }
        Header[] headers = response.getAllHeaders();

        if (wire.isDebugEnabled()) {
            wire.debug(status.toString());
            for (Header h : headers) {
                if (h.getValue() != null) {
                    wire.debug(h.getName() + ": " + h.getValue().trim());
                } else {
                    wire.debug(h.getName() + ":");
                }
            }
            wire.debug("");
        }
        if (status.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) {
            return null;
        }
        if (status.getStatusCode() != HttpServletResponse.SC_OK
                && status.getStatusCode() != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) {
            logger.error("get(): Expected OK for GET request, got " + status.getStatusCode());

            HttpEntity entity = response.getEntity();
            String body;

            if (entity == null) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), "An error was returned without explanation");
            }
            try {
                body = EntityUtils.toString(entity);
            } catch (IOException e) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), e.getMessage());
            }
            if (wire.isDebugEnabled()) {
                wire.debug(body);
            }
            wire.debug("");
            AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body);

            if (items == null) {
                return null;
            }
            logger.error("get(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details);
            throw new AzureException(items);
        } else {
            HttpEntity entity = response.getEntity();

            if (entity == null) {
                return null;
            }
            InputStream input;

            try {
                input = entity.getContent();
            } catch (IOException e) {
                logger.error(
                        "get(): Failed to read response error due to a cloud I/O error: " + e.getMessage());
                if (logger.isTraceEnabled()) {
                    e.printStackTrace();
                }
                throw new CloudException(e);
            }
            return parseResponse(input, true);
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + AzureMethod.class.getName() + ".getStream()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("--------------------------------------------------------> " + uri.toASCIIString());
        }
    }
}

From source file:org.ldp4j.server.IntegrationTestHelper.java

public String httpRequest(final HttpUriRequest request) throws Exception {
    final AtomicReference<String> body = new AtomicReference<String>();
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            String responseBody = logResponse(response);
            // TODO: Add validation mechanism here
            body.set(responseBody);/*from   w w  w  .  ja v  a2  s.  co m*/
            return responseBody;
        }

        private final String NL = System.getProperty("line.separator");

        private String logResponse(final HttpResponse response) throws IOException {
            HttpEntity entity = response.getEntity();
            String responseBody = entity != null ? EntityUtils.toString(entity) : null;
            if (logger.isDebugEnabled()) {
                StringBuilder builder = new StringBuilder();
                builder.append("-- REQUEST COMPLETED -------------------------").append(NL);
                builder.append("-- RESPONSE INIT -----------------------------").append(NL);
                builder.append(response.getStatusLine().toString()).append(NL);
                builder.append("-- RESPONSE HEADERS---------------------------").append(NL);
                for (org.apache.http.Header h : response.getAllHeaders()) {
                    builder.append(h.getName() + " : " + h.getValue()).append(NL);
                }
                if (responseBody != null && responseBody.length() > 0) {
                    builder.append("-- RESPONSE BODY -----------------------------").append(NL);
                    builder.append(responseBody).append(NL);
                }
                builder.append("-- RESPONSE END ------------------------------");
                logger.debug(builder.toString());
            }
            return responseBody;
        }
    };
    logger.debug("-- REQUEST INIT -------------------------------");
    logger.debug(request.getRequestLine().toString());
    httpclient.execute(request, responseHandler);
    return body.get();
}

From source file:nl.opengeogroep.filesetsync.client.FilesetSyncer.java

private void retrieveFilesetList() throws IOException {

    final boolean cachedFileList = state.getFileListDate() != null
            && state.getFileListRemotePath().equals(fs.getRemote())
            && (!fs.isHash() || state.isFileListHashed()) && SyncJobState.haveCachedFileList(fs.getName());

    String s = "Retrieving file list";
    if (cachedFileList) {
        s += String.format(" (last file list cached at %s)", FormatUtil.dateToString(state.getFileListDate()));
    }// w  w  w. jav a  2 s  . co  m
    action(s);

    try (CloseableHttpClient httpClient = HttpClientUtil.get()) {
        HttpUriRequest get = RequestBuilder.get().setUri(serverUrl + "list/" + fs.getRemote())
                .addParameter("hash", fs.isHash() + "").addParameter("regexp", fs.getRegexp()).build();
        if (cachedFileList) {
            get.addHeader(HttpHeaders.IF_MODIFIED_SINCE, HttpUtil.formatDate(state.getFileListDate()));
        }
        addExtraHeaders(get);
        // Request poorly encoded text format
        get.addHeader(HttpHeaders.ACCEPT, "text/plain");

        ResponseHandler<List<FileRecord>> rh = new ResponseHandler<List<FileRecord>>() {
            @Override
            public List handleResponse(HttpResponse hr) throws ClientProtocolException, IOException {
                log.info("< " + hr.getStatusLine());

                int status = hr.getStatusLine().getStatusCode();
                if (status == SC_NOT_MODIFIED) {
                    return null;
                } else if (status >= SC_OK && status < 300) {
                    HttpEntity entity = hr.getEntity();
                    if (entity == null) {
                        throw new ClientProtocolException("No response entity, invalid server URL?");
                    }
                    try (InputStream in = entity.getContent()) {
                        return Protocol.decodeFilelist(in);
                    }
                } else {
                    if (log.isTraceEnabled()) {
                        String entity = hr.getEntity() == null ? null : EntityUtils.toString(hr.getEntity());
                        log.trace("Response body: " + entity);
                    } else {
                        EntityUtils.consumeQuietly(hr.getEntity());
                    }
                    throw new ClientProtocolException("Server error: " + hr.getStatusLine());
                }
            }
        };

        log.info("> " + get.getRequestLine());
        fileList = httpClient.execute(get, rh);

        if (fileList == null) {
            log.info("Cached file list is up-to-date");

            fileList = SyncJobState.readCachedFileList(fs.getName());
        } else {
            log.info("Filelist returned " + fileList.size() + " files");

            /* Calculate last modified client-side, requires less server
             * memory
             */

            long lastModified = -1;
            for (FileRecord fr : fileList) {
                lastModified = Math.max(lastModified, fr.getLastModified());
            }
            if (lastModified != -1) {
                state.setFileListRemotePath(fs.getRemote());
                state.setFileListDate(new Date(lastModified));
                state.setFileListHashed(fs.isHash());
                SyncJobState.writeCachedFileList(fs.getName(), fileList);
                SyncJobStatePersistence.persist();
            }
        }
    }
}

From source file:com.joyent.manta.http.StandardHttpHelper.java

@Override
public MantaObjectInputStream httpRequestAsInputStream(final HttpUriRequest request,
        final MantaHttpHeaders requestHeaders) throws IOException {
    if (requestHeaders != null) {
        MantaHttpRequestFactory.addHeaders(request, requestHeaders.asApacheHttpHeaders());
    }//from   w ww  .ja  va2 s.co  m

    final int expectedHttpStatus;

    if (requestHeaders != null && requestHeaders.containsKey(HttpHeaders.RANGE)) {
        expectedHttpStatus = HttpStatus.SC_PARTIAL_CONTENT;
    } else {
        expectedHttpStatus = HttpStatus.SC_OK;
    }

    final Function<CloseableHttpResponse, MantaObjectInputStream> responseAction = response -> {
        final MantaHttpHeaders responseHeaders = new MantaHttpHeaders(response.getAllHeaders());
        final String path = request.getURI().getPath();
        // MantaObjectResponse expects to be constructed with the
        // encoded path, which it then decodes when a caller does
        // getPath.  However, here the HttpUriRequest has already
        // decoded.
        final MantaObjectResponse metadata = new MantaObjectResponse(MantaUtils.formatPath(path),
                responseHeaders);

        if (metadata.isDirectory()) {
            final String msg = "Directories do not have data, so data streams "
                    + "from directories are not possible.";
            final MantaUnexpectedObjectTypeException exception = new MantaUnexpectedObjectTypeException(msg,
                    ObjectType.FILE, ObjectType.DIRECTORY);
            exception.setContextValue("path", path);

            if (metadata.getHttpHeaders() != null) {
                exception.setResponseHeaders(metadata.getHttpHeaders());
            }

            throw exception;
        }

        final HttpEntity entity = response.getEntity();
        if (entity == null) {
            final String msg = "Can't process null response entity.";
            final MantaClientException exception = new MantaClientException(msg);
            exception.setContextValue("uri", request.getRequestLine().getUri());
            exception.setContextValue("method", request.getRequestLine().getMethod());

            throw exception;
        }

        final InputStream httpEntityStream;
        try {
            httpEntityStream = entity.getContent();
        } catch (IOException ioe) {
            String msg = String.format("Error getting stream from entity content for path: %s", path);
            MantaObjectException e = new MantaObjectException(msg, ioe);
            e.setContextValue("path", path);
            HttpHelper.annotateContextedException(e, request, response);
            throw e;
        }

        final InputStream backingStream;
        final InputStreamContinuator continuator = constructContinuatorForCompatibleRequest(request, response);
        if (continuator != null) {
            backingStream = new AutoContinuingInputStream(httpEntityStream, continuator);
        } else {
            backingStream = httpEntityStream;
        }

        return new MantaObjectInputStream(metadata, response, backingStream);
    };

    return executeRequest(request, expectedHttpStatus, responseAction, false, "GET    {} response [{}] {} ");
}

From source file:com.googlecode.jdeltasync.DeltaSyncClient.java

/**
 * Slightly modified version of {@link DefaultRedirectStrategy#getLocationURI(HttpRequest, HttpResponse, HttpContext)}
 * which also adds the query string from the original request URI to the new URI.
 *//*from  w  w  w  . j  a v a 2 s. c om*/
private URI getRedirectLocationURI(IDeltaSyncSession session, HttpUriRequest request, HttpResponse response,
        HttpContext context) throws DeltaSyncException {

    //get the location header to find out where to redirect to
    Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new DeltaSyncException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }
    String location = locationHeader.getValue();
    if (session.getLogger().isDebugEnabled()) {
        session.getLogger().debug("Redirect requested to location '" + location + "'");
    }

    URI uri = null;
    try {
        uri = new URI(location);
        if (request.getURI().getRawQuery() != null) {
            String query = request.getURI().getRawQuery();
            uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(),
                    query, uri.getFragment());
        }
    } catch (URISyntaxException ex) {
        throw new DeltaSyncException("Invalid redirect URI: " + location, ex);
    }

    final HttpClientContext clientContext = HttpClientContext.adapt(context);
    final RequestConfig config = clientContext.getRequestConfig();

    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    try {
        if (!uri.isAbsolute()) {
            if (config.isRelativeRedirectsAllowed()) {
                throw new DeltaSyncException("Relative redirect location '" + uri + "' not allowed");
            }
            // Adjust location URI
            HttpHost target = clientContext.getTargetHost();
            if (target == null) {
                throw new IllegalStateException("Target host not available " + "in the HTTP context");
            }

            URI requestURI = new URI(request.getRequestLine().getUri());
            URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, false);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        }
    } catch (URISyntaxException ex) {
        throw new DeltaSyncException(ex.getMessage(), ex);
    }

    RedirectLocations redirectLocations = (RedirectLocations) clientContext
            .getAttribute("http.protocol.redirect-locations");
    if (redirectLocations == null) {
        redirectLocations = new RedirectLocations();
        context.setAttribute("http.protocol.redirect-locations", redirectLocations);
    }

    if (config.isCircularRedirectsAllowed()) {
        URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (URISyntaxException ex) {
                throw new DeltaSyncException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new DeltaSyncException("Circular redirect to '" + redirectURI + "'");
        } else {
            redirectLocations.add(redirectURI);
        }
    }

    return uri;
}

From source file:org.ldp4j.server.ServerFrontendTestHelper.java

public Metadata httpRequest(final HttpUriRequest request) throws Exception {
    final Metadata metadata = new Metadata();
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            String responseBody = logResponse(response);
            // TODO: Add validation mechanism here
            metadata.body = responseBody;
            Header etagHeader = response.getFirstHeader(HttpHeaders.ETAG);
            if (etagHeader != null) {
                metadata.etag = etagHeader.getValue();
            }/*  w  w w .java 2  s  .  com*/
            Header lastModifiedHeader = response.getFirstHeader(HttpHeaders.LAST_MODIFIED);
            if (lastModifiedHeader != null) {
                metadata.lastModified = lastModifiedHeader.getValue();
            }
            Header locationHeader = response.getFirstHeader(HttpHeaders.LOCATION);
            if (locationHeader != null) {
                metadata.location = locationHeader.getValue();
            }
            return responseBody;
        }

        private final String NL = System.getProperty("line.separator");

        private String logResponse(final HttpResponse response) throws IOException {
            HttpEntity entity = response.getEntity();
            String responseBody = entity != null ? EntityUtils.toString(entity) : null;
            if (logger.isDebugEnabled()) {
                StringBuilder builder = new StringBuilder();
                builder.append("-- REQUEST COMPLETED -------------------------").append(NL);
                builder.append("-- RESPONSE INIT -----------------------------").append(NL);
                builder.append(response.getStatusLine().toString()).append(NL);
                builder.append("-- RESPONSE HEADERS---------------------------").append(NL);
                for (org.apache.http.Header h : response.getAllHeaders()) {
                    builder.append(h.getName() + " : " + h.getValue()).append(NL);
                }
                if (responseBody != null && responseBody.length() > 0) {
                    builder.append("-- RESPONSE BODY -----------------------------").append(NL);
                    builder.append(responseBody).append(NL);
                }
                builder.append("-- RESPONSE END ------------------------------");
                logger.debug(builder.toString());
            }
            return responseBody;
        }
    };
    logger.debug("-- REQUEST INIT -------------------------------");
    logger.debug(request.getRequestLine().toString());
    httpclient.execute(request, responseHandler);
    return metadata;
}

From source file:org.ldp4j.server.testing.ServerFrontendTestHelper.java

public Metadata httpRequest(final HttpUriRequest request) throws Exception {
    final Metadata metadata = new Metadata();
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            String responseBody = logResponse(response);
            // TODO: Add validation mechanism here
            metadata.status = response.getStatusLine().getStatusCode();
            metadata.body = responseBody;
            Header etagHeader = response.getFirstHeader(HttpHeaders.ETAG);
            if (etagHeader != null) {
                metadata.etag = etagHeader.getValue();
            }/* w  w  w. j  a v a 2 s.c  o m*/
            Header lastModifiedHeader = response.getFirstHeader(HttpHeaders.LAST_MODIFIED);
            if (lastModifiedHeader != null) {
                metadata.lastModified = lastModifiedHeader.getValue();
            }
            Header locationHeader = response.getFirstHeader(HttpHeaders.LOCATION);
            if (locationHeader != null) {
                metadata.location = locationHeader.getValue();
            }
            Header contentType = response.getFirstHeader(HttpHeaders.CONTENT_TYPE);
            if (contentType != null) {
                metadata.contentType = contentType.getValue();
            }
            Header contentLanguage = response.getFirstHeader(HttpHeaders.CONTENT_LANGUAGE);
            if (contentLanguage != null) {
                metadata.language = Locale.forLanguageTag(contentLanguage.getValue());
            }
            return responseBody;
        }

        private final String NL = System.getProperty("line.separator");

        private String logResponse(final HttpResponse response) throws IOException {
            HttpEntity entity = response.getEntity();
            String responseBody = entity != null ? EntityUtils.toString(entity) : null;
            if (logger.isDebugEnabled()) {
                StringBuilder builder = new StringBuilder();
                builder.append("-- REQUEST COMPLETED -------------------------").append(NL);
                builder.append("-- RESPONSE INIT -----------------------------").append(NL);
                builder.append(response.getStatusLine().toString()).append(NL);
                builder.append("-- RESPONSE HEADERS---------------------------").append(NL);
                for (org.apache.http.Header h : response.getAllHeaders()) {
                    builder.append(h.getName() + " : " + h.getValue()).append(NL);
                }
                if (responseBody != null && responseBody.length() > 0) {
                    builder.append("-- RESPONSE BODY -----------------------------").append(NL);
                    builder.append(responseBody).append(NL);
                }
                builder.append("-- RESPONSE END ------------------------------");
                logger.debug(builder.toString());
            }
            return responseBody;
        }
    };
    logger.debug("-- REQUEST INIT -------------------------------");
    logger.debug(request.getRequestLine().toString());
    httpclient.execute(request, responseHandler);
    return metadata;
}

From source file:net.tsz.afinal.http.HttpHandler.java

private void makeRequestWithRetries(HttpUriRequest request) throws IOException {
    if (isResume && targetUrl != null) {
        File downloadFile = new File(targetUrl);
        long fileLen = 0;
        if (downloadFile.isFile() && downloadFile.exists()) {
            fileLen = downloadFile.length();
        }//from w  w w  .j  a v  a  2s.c o  m
        if (fileLen > 0)
            request.setHeader("RANGE", "bytes=" + fileLen + "-");
    }

    boolean retry = true;
    IOException cause = null;
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();//?
    while (retry) {
        try {
            if (isCancelled()) {
                return;
            }

            //POST:?;GET:?
            String requestUrl = request.getURI().toString();
            String requestMethod = request.getMethod();
            ZLogger.d(String.format("<%d><%s> %s", executionCount, requestMethod, requestUrl));

            for (Header header : request.getAllHeaders()) {
                ZLogger.d(String.format("<%s>:<%s>", header.getName(), header.getValue()));
            }

            //??url
            StringBuilder requestParams = new StringBuilder();
            if (requestMethod.equals(POST)) {
                HttpEntityEnclosingRequestBase requestBase = (HttpEntityEnclosingRequestBase) request;
                if (requestBase != null) {
                    HttpEntity entity = requestBase.getEntity();
                    if (entity != null) {
                        InputStream is = entity.getContent();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                        String line = null;
                        try {
                            while ((line = reader.readLine()) != null) {
                                //                            sb.append(line + "/n");
                                //                                Log.d("Nat: makeRequestWithRetries.request.Params.line", line);
                                requestParams.append(line);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            ZLogger.ef(e.toString());
                        } finally {
                            try {
                                is.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    //                        byte[] paramsArray = EntityUtils.toByteArray(entity);
                    //                        String paramsStr = EntityUtils.toString(entity, "UTF-8");
                    //                        Log.d("Nat: makeRequestWithRetries.request.Params(2)", paramsStr);
                    //                        Log.d("Nat: makeRequestWithRetries.request.Params(3)", EntityUtils.toString(entity));
                }

                //                    Log.d("Nat: makeRequestWithRetries.request.Params(RAW)", requestParams.toString());
            }

            //
            HttpResponse response = client.execute(request, context);
            //                for(Header header : response.getAllHeaders()){
            //                    Log.d("Nat", String.format(" makeRequestWithRetries.respoonse.header <%s><%s>", header.getName(), header.getValue()));
            //                }

            if (isCancelled()) {
                ZLogger.d("Nat: makeRequestWithRetries", "request caneled.");
                return;
            }

            //POST:?;GET:?
            request.getRequestLine();//GET
            ZLogger.d(request.getRequestLine().toString());
            /*if (request.getMethod().equals("post")) {
            HttpParams params = request.getParams();
             params.setParameter(NetFactory.CLIENTSESSION, "");
            request.snetParams(params);
            }*/

            //?????()
            //executionCount < 1,?????
            if (response.containsHeader("needLogin")/* && executionCount < 1*/) {
                //?url?JSSIONID??cookie.
                //?(?),sessionId
                String newSid = MfhLoginService.get().doLogin();
                if (newSid == null) {
                    //TODO
                    //,?
                    //                        Intent intent = new Intent(Constants.ACTION_REDIRECT_TO_LOGIN_H5);
                    //                        BizApplication.getAppContext().sendBroadcast(intent);
                    //                        break;
                } else {
                    String cookie = String.format("%s=%s", FinalHttp.KEY_JSESSIONID, newSid);
                    request.addHeader(FinalHttp.HEADER_SET_COOKIE, cookie);
                    request.addHeader(FinalHttp.HEADER_COOKIE, cookie);
                    request.addHeader(FinalHttp.HEADER_cookie, cookie);
                    // ?
                    //                        MsgBridgeUtil.register();

                    if (requestMethod.equals(POST)) {
                        //                        //EntityJSSIONID
                        String newParams = replaceParam(requestParams.toString(), JSESSIONID, newSid);
                        //                            HttpEntity entity = new StringEntity(newParams);
                        HttpEntity entity = convertToAjaxParams(newParams).getEntity();
                        ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
                    } else if (requestMethod.equals(GET)) {
                        //URLJSSIONID
                        String newRequestUrl = replaceParam(requestUrl, JSESSIONID, newSid);
                        //                            newRequestUrl = replaceParam(newRequestUrl, "lastupdate", "0");
                        URI uri = new URI(newRequestUrl);
                        //                            Log.d("Nat: makeRequestWithRetries.autoLogin.URI", uri.toString());
                        //                                HttpEntityEnclosingRequestBase requestFact = (HttpEntityEnclosingRequestBase)request;
                        //                                requestFact.setURI(uri);
                        ((HttpEntityEnclosingRequestBase) request).setURI(uri);
                    }
                }

                //TODO,?
                retry = (++executionCount <= MAX_RETRY_TIMES)
                        || retryHandler.retryRequest(new IOException("Exception"), executionCount, context);
                //                    ZLogger.d(String.format("%s  %d", retry ? "?" : "??", executionCount));
                if (retry) {
                    continue;
                }
            }

            //?
            handleResponse(response);
            return;
        } catch (UnknownHostException e) {
            ZLogger.e("UnknownHostException:" + e.toString());
            publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host");
            return;
        } catch (IOException e) {
            ZLogger.e("IOException: " + e.toString());
            cause = e;
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
            publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host");
        } catch (NullPointerException e) {
            if (e != null) {
                ZLogger.e("NullPointerException: " + e.toString());
                // here's a bug in HttpClient 4.0.x that on some occasions causes
                // DefaultRequestExecutor to throw an NPE, see
                // http://code.google.com/p/android/issues/detail?id=5255
                cause = new IOException("NPE in HttpClient: " + e.getMessage());
                retry = retryHandler.retryRequest(cause, ++executionCount, context);
            } else {
                ZLogger.e("NullPointerException: e is null");
            }
            publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host");
        } catch (Exception e) {
            ZLogger.e("Exception: " + e.toString());
            cause = new IOException("Unhandled Exception" + e.getMessage());
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
            publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host");
        }
    }

    // cleaned up to throw IOException
    if (cause != null) {
        throw cause;
    }
    //        else{
    //            //TODO
    //            throw new IOException("");
    //        }
}

From source file:nl.opengeogroep.safetymaps.routing.service.OpenRouteService.java

@Override
public RoutingResult getRoute(RoutingRequest request) throws RoutingException {

    RoutingResult result;//from  w  w  w  .  j  a  v a2  s .  c  o  m
    try {
        CoordinateReferenceSystem crs = CRS.decode("epsg:28992");
        CoordinateReferenceSystem serviceCrs = CRS.decode("epsg:4326");
        MathTransform transform = CRS.findMathTransform(crs, serviceCrs, true);

        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
        Coordinate coord = new Coordinate(request.getFromX(), request.getFromY());
        Point from = geometryFactory.createPoint(coord);
        coord = new Coordinate(request.getToX(), request.getToY());
        Point to = geometryFactory.createPoint(coord);

        Point fromTransformed = (Point) JTS.transform(from, transform);
        Point toTransformed = (Point) JTS.transform(to, transform);

        log.info("Reprojected destination point to service CRS: " + toTransformed);

        try (CloseableHttpClient client = getClient()) {
            HttpUriRequest get = RequestBuilder.get().setUri("https://api.openrouteservice.org/directions")
                    .addHeader("Accept", "text/json; charset=utf-8").addParameter("api_key", apiKey)
                    .addParameter("coordinates",
                            fromTransformed.getY() + "," + fromTransformed.getX() + "|" + toTransformed.getY()
                                    + "," + toTransformed.getX())
                    .addParameter("profile", profile).addParameter("preference", preference)
                    .addParameter("format", "geojson").addParameter("language", "nl")
                    //.addParameter("instructions", "false")
                    .addParameter("elevation", "false").addParameter("extra_info", "").build();

            log.info("GET > " + get.getRequestLine());
            String response = client.execute(get, new ResponseHandler<String>() {
                @Override
                public String handleResponse(HttpResponse hr) {
                    log.trace("< " + hr.getStatusLine());
                    String entity = null;
                    try {
                        entity = IOUtils.toString(hr.getEntity().getContent(), "UTF-8");
                    } catch (IOException e) {
                    }
                    if (hr.getStatusLine().getStatusCode() != SC_OK) {
                        log.error("HTTP error: " + hr.getStatusLine() + ", " + entity);
                    }
                    log.trace("< entity: " + entity);
                    return entity;
                }
            });
            if (response != null) {
                JSONObject res = new JSONObject(response);
                log.info("JSON response: " + res.toString(4));

                result = new RoutingResult(true, res);
                result.setDistance(calculateDistance(res));
                result.setRoute(res);
            } else {
                result = new RoutingResult(false, "Error calculating route: null response", null);
            }
        }

    } catch (Exception e) {
        log.error("Error calculating route", e);
        result = new RoutingResult(false, "Error calculating route: " + e.getMessage(), e);
    }
    return result;
}