Search in sources :

Example 31 with NoHttpResponseException

use of org.apache.http.NoHttpResponseException in project neo-java by coranos.

the class RpcClientUtil method post.

/**
 * posts a request.
 *
 * @param timeoutMillis
 *            the time to wait, in milliseconds. (used for SocketTimeout,
 *            ConnectTimeout, and ConnectionRequestTimeout)
 * @param rpcNode
 *            the RPC node to use.
 * @param silentErrors
 *            if false, log the error to LOG.error().
 * @param inputJson
 *            the input JSON to use.
 * @return the response, or null if an error occurs due to a timeout.
 */
public static JSONObject post(final long timeoutMillis, final String rpcNode, final boolean silentErrors, final JSONObject inputJson) {
    LOG.debug("inputJson:{}", inputJson);
    final StringEntity input = new StringEntity(inputJson.toString(), ContentType.APPLICATION_JSON);
    final HttpPost post = new HttpPost(rpcNode);
    final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout((int) timeoutMillis).setConnectTimeout((int) timeoutMillis).setConnectionRequestTimeout((int) timeoutMillis).build();
    post.setConfig(requestConfig);
    post.setEntity(input);
    final CloseableHttpClient client = HttpClients.createDefault();
    final String str;
    try {
        final CloseableHttpResponse response = client.execute(post);
        LOG.debug("status:{}", response.getStatusLine());
        final HttpEntity entity = response.getEntity();
        str = EntityUtils.toString(entity);
    } catch (final ConnectTimeoutException | SocketTimeoutException | NoHttpResponseException | SocketException e) {
        if (!silentErrors) {
            LOG.error("post {} {} connection error:{}", rpcNode, inputJson, e.getMessage());
        }
        return null;
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
    if (!str.startsWith("{")) {
        if (!silentErrors) {
            LOG.error("post {} {} json error:\"{}\"", rpcNode, inputJson, str);
        }
        return null;
    }
    final JSONObject outputJson = new JSONObject(str);
    LOG.debug("outputJson:{}", outputJson.toString(2));
    return outputJson;
}
Also used : NoHttpResponseException(org.apache.http.NoHttpResponseException) HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) SocketException(java.net.SocketException) HttpEntity(org.apache.http.HttpEntity) IOException(java.io.IOException) StringEntity(org.apache.http.entity.StringEntity) SocketTimeoutException(java.net.SocketTimeoutException) JSONObject(org.json.JSONObject) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 32 with NoHttpResponseException

use of org.apache.http.NoHttpResponseException in project NetDiscovery by fengzhizi715.

the class RetryHandler method retryRequest.

@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    if (executionCount >= 3) {
        // 如果已经重试了3次,就放弃
        return false;
    }
    if (exception instanceof NoHttpResponseException) {
        // 如果服务器丢掉了连接,那么就重试
        return true;
    }
    if (exception instanceof SSLHandshakeException) {
        // 不要重试SSL握手异常
        return false;
    }
    if (exception instanceof InterruptedIOException) {
        // 超时
        return true;
    }
    if (exception instanceof UnknownHostException) {
        // 目标服务器不可达
        return false;
    }
    if (exception instanceof ConnectTimeoutException) {
        // 连接被拒绝
        return false;
    }
    if (exception instanceof SSLException) {
        // ssl握手异常
        return false;
    }
    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();
    // 如果请求是幂等的,就再次尝试
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return true;
    }
    return false;
}
Also used : NoHttpResponseException(org.apache.http.NoHttpResponseException) HttpRequest(org.apache.http.HttpRequest) InterruptedIOException(java.io.InterruptedIOException) UnknownHostException(java.net.UnknownHostException) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) SSLException(javax.net.ssl.SSLException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 33 with NoHttpResponseException

use of org.apache.http.NoHttpResponseException in project qi4j-sdk by Qi4j.

the class SecureJettyServiceTest method testNoSSL.

@Test
public // This test exists for demonstration purpose only, it do not test usefull things but it's on purpose
void testNoSSL() throws IOException {
    try {
        HttpGet get = new HttpGet("http://127.0.0.1:8441/hello");
        defaultHttpClient.execute(get);
        fail("We could reach the HTTPS connector using a HTTP url, that's no good");
    } catch (NoHttpResponseException ex) {
    // Expected
    }
}
Also used : NoHttpResponseException(org.apache.http.NoHttpResponseException) HttpGet(org.apache.http.client.methods.HttpGet) Test(org.junit.Test)

Example 34 with NoHttpResponseException

use of org.apache.http.NoHttpResponseException in project newsrob by marianokamp.

the class WebPageDownloadTask method call.

@Override
public Void call() throws Exception {
    try {
        U.setLowPrio();
        Context ctx = entryManager.getContext();
        // Tracking the hosts that timed out once, so
        // that we then can skip trying other articles for that host.
        // This is for pages like FAZ.net
        Timing tInner = new Timing("Downloading page " + pageUrl, ctx);
        final String downloadHost = new URL(entry.getAlternateHRef()).getHost().toString();
        boolean downloadingFromInstapaper = false;
        try {
            if (downloadHost.contains("instapaper")) {
                instapaperLock.lock();
                downloadingFromInstapaper = true;
            }
            if (downloadContext.containsTimedOutHost(downloadHost)) {
                Log.w(SynchronizationService.class.getSimpleName(), "Article " + entry.getTitle() + " not downloaded, because the host is on the timeout list.");
                entry.setError("This host (" + downloadHost + ") timed out during the sync. We'll try again during next sync.");
            } else {
                // check free space
                float freeSpaceLeft = fileContextAdapter.megaBytesFree();
                Log.d(TAG, String.format("Free space remaining for downloads: %.2f MB.", freeSpaceLeft));
                if (freeSpaceLeft < 0) {
                    PL.log(TAG + ": Oh no, free space left is a negative value ;-( Ignoring it.", ctx);
                } else if (freeSpaceLeft < fileContextAdapter.megaBytesThreshold()) {
                    PL.log(TAG + ": Not enough space left to download page.", ctx);
                    entryManager.getNewsRobNotificationManager().createSyncSpaceExceededProblemNotification(fileContextAdapter.megaBytesThreshold());
                    return null;
                }
                final long downloadStartedAt = System.currentTimeMillis();
                WebPageDownloadDirector.downloadWebPage(entryShortAtomId, new URL(pageUrl), fileContextAdapter, job, summary, downloadCompleteWebPage, entryManager, manualSync);
                generatePreview(ctx);
                entry.setDownloaded(downloadCompleteWebPage ? Entry.STATE_DOWNLOADED_FULL_PAGE : Entry.STATE_DOWNLOADED_FEED_CONTENT);
                entry.setError("Download took " + (System.currentTimeMillis() - downloadStartedAt) + " ms.");
            }
        } catch (Exception e) {
            Log.e(TAG, "Problem dowloading page " + entry.getAlternateHRef() + ".", e);
            Throwable cause = null;
            if (e instanceof DownloadException) {
                cause = ((DownloadException) e).getCause();
                Log.d(TAG, "DownloadException cause=" + cause);
            } else
                Log.d(TAG, "Exception=" + e);
            boolean downloadError = false;
            if (e instanceof DownloadTimedOutException) {
                Log.w(SynchronizationService.class.getSimpleName(), "Download for " + entry.getAlternateHRef() + " timed out. Adding host to timed out hosts list.");
                downloadContext.addTimedOutHost(downloadHost);
                entry.setError("Download timed out.");
                entry.setDownloaded(Entry.STATE_DOWNLOAD_ERROR);
            } else {
                if (e instanceof DownloadCancelledException || cause != null && (cause instanceof FileNotFoundException || cause instanceof SocketTimeoutException || cause instanceof SocketException || cause instanceof NoHttpResponseException || cause instanceof UnknownHostException || cause instanceof DownloadCancelledException)) {
                    Log.d(TAG, "Caught a FNFE");
                } else {
                    Log.d(TAG, "Marked download as error.");
                    downloadError = true;
                }
                StringBuilder renderedStackTrace = new StringBuilder();
                U.renderStackTrace(e, renderedStackTrace);
                entry.setError(cause != null ? "Cause: " + cause.getClass().getSimpleName() + ": " + cause.getMessage() : e.getClass().getSimpleName() + ": " + e.getMessage() + "\nStacktrace: " + renderedStackTrace);
                entry.setDownloaded(downloadError ? Entry.STATE_DOWNLOAD_ERROR : Entry.STATE_NOT_DOWNLOADED);
            }
        } finally {
            if (instapaperLock.isHeldByCurrentThread())
                instapaperLock.unlock();
        }
        entryManager.updatedDownloaded(entry);
        job.actual++;
        entryManager.fireModelUpdated(entry.getAtomId());
        entryManager.fireStatusUpdated();
        tInner.stop();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    return null;
}
Also used : Context(android.content.Context) DownloadContext(com.newsrob.download.DownloadContext) NoHttpResponseException(org.apache.http.NoHttpResponseException) DownloadTimedOutException(com.newsrob.download.DownloadTimedOutException) SocketException(java.net.SocketException) UnknownHostException(java.net.UnknownHostException) FileNotFoundException(java.io.FileNotFoundException) DownloadCancelledException(com.newsrob.download.DownloadCancelledException) URL(java.net.URL) DownloadTimedOutException(com.newsrob.download.DownloadTimedOutException) NoHttpResponseException(org.apache.http.NoHttpResponseException) ParseException(java.text.ParseException) FileNotFoundException(java.io.FileNotFoundException) DownloadException(com.newsrob.download.DownloadException) SAXException(org.xml.sax.SAXException) DownloadCancelledException(com.newsrob.download.DownloadCancelledException) ClientProtocolException(org.apache.http.client.ClientProtocolException) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SocketTimeoutException(java.net.SocketTimeoutException) DownloadException(com.newsrob.download.DownloadException) Timing(com.newsrob.util.Timing)

Example 35 with NoHttpResponseException

use of org.apache.http.NoHttpResponseException in project calcite-avatica by apache.

the class AvaticaCommonsHttpClientImplTest method testRetryOnMissingHttpResponse.

@Test
public void testRetryOnMissingHttpResponse() throws Exception {
    final byte[] requestBytes = "fake_request".getBytes(UTF_8);
    final CloseableHttpResponse badResponse = mock(CloseableHttpResponse.class);
    final CloseableHttpResponse goodResponse = mock(CloseableHttpResponse.class);
    final StatusLine badStatusLine = mock(StatusLine.class);
    final StatusLine goodStatusLine = mock(StatusLine.class);
    final StringEntity responseEntity = new StringEntity("success");
    final Answer<CloseableHttpResponse> failThenSucceed = new Answer<CloseableHttpResponse>() {

        private int iteration = 0;

        @Override
        public CloseableHttpResponse answer(InvocationOnMock invocation) throws Throwable {
            iteration++;
            if (1 == iteration) {
                throw new NoHttpResponseException("The server didn't respond!");
            } else {
                return goodResponse;
            }
        }
    };
    final AvaticaCommonsHttpClientImpl client = mock(AvaticaCommonsHttpClientImpl.class);
    when(client.send(any(byte[].class))).thenCallRealMethod();
    when(client.execute(any(HttpPost.class), any(HttpClientContext.class))).then(failThenSucceed);
    when(badResponse.getStatusLine()).thenReturn(badStatusLine);
    when(badStatusLine.getStatusCode()).thenReturn(HttpURLConnection.HTTP_UNAVAILABLE);
    when(goodResponse.getStatusLine()).thenReturn(goodStatusLine);
    when(goodStatusLine.getStatusCode()).thenReturn(HttpURLConnection.HTTP_OK);
    when(goodResponse.getEntity()).thenReturn(responseEntity);
    byte[] responseBytes = client.send(requestBytes);
    assertEquals("success", new String(responseBytes, UTF_8));
}
Also used : StatusLine(org.apache.http.StatusLine) NoHttpResponseException(org.apache.http.NoHttpResponseException) StringEntity(org.apache.http.entity.StringEntity) Answer(org.mockito.stubbing.Answer) HttpPost(org.apache.http.client.methods.HttpPost) InvocationOnMock(org.mockito.invocation.InvocationOnMock) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) Test(org.junit.Test)

Aggregations

NoHttpResponseException (org.apache.http.NoHttpResponseException)38 IOException (java.io.IOException)13 SocketException (java.net.SocketException)12 StatusLine (org.apache.http.StatusLine)12 ConnectTimeoutException (org.apache.http.conn.ConnectTimeoutException)11 SocketTimeoutException (java.net.SocketTimeoutException)10 ParserCursor (org.apache.http.message.ParserCursor)9 UnknownHostException (java.net.UnknownHostException)8 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)8 HttpRequest (org.apache.http.HttpRequest)7 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)7 ConnectException (java.net.ConnectException)6 HttpEntityEnclosingRequest (org.apache.http.HttpEntityEnclosingRequest)6 InterruptedIOException (java.io.InterruptedIOException)5 SSLException (javax.net.ssl.SSLException)5 HashMap (java.util.HashMap)4 HttpEntity (org.apache.http.HttpEntity)4 RequestConfig (org.apache.http.client.config.RequestConfig)4 HttpPost (org.apache.http.client.methods.HttpPost)4 SolrException (org.apache.solr.common.SolrException)4