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;
}
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;
}
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
}
}
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;
}
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));
}
Aggregations