use of org.apache.http.conn.ConnectTimeoutException in project Douya by DreaminginCodeZH.
the class BasicNetwork method performRequest.
@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
long requestStart = SystemClock.elapsedRealtime();
while (true) {
HttpResponse httpResponse = null;
byte[] responseContents = null;
Map<String, String> responseHeaders = Collections.emptyMap();
try {
// Gather headers.
Map<String, String> headers = new HashMap<>();
addCacheHeaders(headers, request.getCacheEntry());
httpResponse = mHttpStack.performRequest(request, headers);
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
responseHeaders = convertHeaders(httpResponse.getAllHeaders());
// Handle cache validation.
if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
Cache.Entry entry = request.getCacheEntry();
if (entry == null) {
return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, null, responseHeaders, true, SystemClock.elapsedRealtime() - requestStart);
}
// A HTTP 304 response does not have all header fields. We
// have to use the header fields from the cache entry plus
// the new ones from the response.
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
entry.responseHeaders.putAll(responseHeaders);
return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, entry.data, entry.responseHeaders, true, SystemClock.elapsedRealtime() - requestStart);
}
// Some responses such as 204s do not have content. We must check.
if (httpResponse.getEntity() != null) {
responseContents = entityToBytes(httpResponse.getEntity());
} else {
// Add 0 byte response as a way of honestly representing a
// no-content request.
responseContents = new byte[0];
}
// if the request is slow, log it.
long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
logSlowRequests(requestLifetime, request, responseContents, statusLine);
if (statusCode < 200 || statusCode > 299) {
throw new IOException();
}
return new NetworkResponse(statusCode, responseContents, responseHeaders, false, SystemClock.elapsedRealtime() - requestStart);
} catch (MalformedURLException e) {
throw new RuntimeException("Bad URL " + request.getUrl(), e);
} catch (SocketTimeoutException e) {
attemptRetryOnException("socket-timeout", request, new TimeoutError());
} catch (ConnectTimeoutException e) {
attemptRetryOnException("connection-timeout", request, new TimeoutError());
} catch (IOException e) {
int statusCode;
if (httpResponse != null) {
statusCode = httpResponse.getStatusLine().getStatusCode();
} else {
// PATCH: Let RetryPolicy decide whether the request should be aborted.
attemptRetryOnException("no-connection", request, new NoConnectionError(e));
continue;
}
VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
if (responseContents != null) {
NetworkResponse networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false, SystemClock.elapsedRealtime() - requestStart);
if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
} else {
// PATCH: Let RetryPolicy decide whether the request should be aborted.
// TODO: Only throw ServerError for 5xx status codes.
attemptRetryOnException("server", request, new ServerError(networkResponse));
}
} else {
// PATCH: Let RetryPolicy decide whether the request should be aborted.
attemptRetryOnException("network", request, new NetworkError());
}
}
}
}
use of org.apache.http.conn.ConnectTimeoutException in project XobotOS by xamarin.
the class PlainSocketFactory method connectSocket.
// non-javadoc, see interface org.apache.http.conn.SocketFactory
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException {
if (host == null) {
throw new IllegalArgumentException("Target host may not be null.");
}
if (params == null) {
throw new IllegalArgumentException("Parameters may not be null.");
}
if (sock == null)
sock = createSocket();
if ((localAddress != null) || (localPort > 0)) {
// we need to bind explicitly
if (localPort < 0)
// indicates "any"
localPort = 0;
InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
sock.bind(isa);
}
int timeout = HttpConnectionParams.getConnectionTimeout(params);
InetSocketAddress remoteAddress;
if (this.nameResolver != null) {
remoteAddress = new InetSocketAddress(this.nameResolver.resolve(host), port);
} else {
remoteAddress = new InetSocketAddress(host, port);
}
try {
sock.connect(remoteAddress, timeout);
} catch (SocketTimeoutException ex) {
throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out");
}
return sock;
}
use of org.apache.http.conn.ConnectTimeoutException in project XobotOS by xamarin.
the class DefaultClientConnectionOperator method openConnection.
// non-javadoc, see interface ClientConnectionOperator
public void openConnection(OperatedClientConnection conn, HttpHost target, InetAddress local, HttpContext context, HttpParams params) throws IOException {
if (conn == null) {
throw new IllegalArgumentException("Connection must not be null.");
}
if (target == null) {
throw new IllegalArgumentException("Target host must not be null.");
}
//@@@ is context allowed to be null?
if (params == null) {
throw new IllegalArgumentException("Parameters must not be null.");
}
if (conn.isOpen()) {
throw new IllegalArgumentException("Connection must not be open.");
}
final Scheme schm = schemeRegistry.getScheme(target.getSchemeName());
final SocketFactory sf = schm.getSocketFactory();
final SocketFactory plain_sf;
final LayeredSocketFactory layered_sf;
if (sf instanceof LayeredSocketFactory) {
plain_sf = staticPlainSocketFactory;
layered_sf = (LayeredSocketFactory) sf;
} else {
plain_sf = sf;
layered_sf = null;
}
InetAddress[] addresses = InetAddress.getAllByName(target.getHostName());
for (int i = 0; i < addresses.length; ++i) {
Socket sock = plain_sf.createSocket();
conn.opening(sock, target);
try {
Socket connsock = plain_sf.connectSocket(sock, addresses[i].getHostAddress(), schm.resolvePort(target.getPort()), local, 0, params);
if (sock != connsock) {
sock = connsock;
conn.opening(sock, target);
}
/*
* prepareSocket is called on the just connected
* socket before the creation of the layered socket to
* ensure that desired socket options such as
* TCP_NODELAY, SO_RCVTIMEO, SO_LINGER will be set
* before any I/O is performed on the socket. This
* happens in the common case as
* SSLSocketFactory.createSocket performs hostname
* verification which requires that SSL handshaking be
* performed.
*/
prepareSocket(sock, context, params);
if (layered_sf != null) {
Socket layeredsock = layered_sf.createSocket(sock, target.getHostName(), schm.resolvePort(target.getPort()), true);
if (layeredsock != sock) {
conn.opening(layeredsock, target);
}
conn.openCompleted(sf.isSecure(layeredsock), params);
} else {
conn.openCompleted(sf.isSecure(sock), params);
}
break;
// BEGIN android-changed
// catch SocketException to cover any kind of connect failure
} catch (SocketException ex) {
if (i == addresses.length - 1) {
ConnectException cause = ex instanceof ConnectException ? (ConnectException) ex : new ConnectException(ex.getMessage(), ex);
throw new HttpHostConnectException(target, cause);
}
// END android-changed
} catch (ConnectTimeoutException ex) {
if (i == addresses.length - 1) {
throw ex;
}
}
}
}
use of org.apache.http.conn.ConnectTimeoutException in project UltimateAndroid by cymcsg.
the class HttpUtils method getResponseFromPostUrl.
public static String getResponseFromPostUrl(String url, List<NameValuePair> params) throws Exception {
String result = null;
// 新建HttpPost对象
HttpPost httpPost = new HttpPost(url);
// 设置字符集
HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
// 设置参数实体
httpPost.setEntity(entity);
// 获取HttpClient对象
HttpClient httpClient = new DefaultHttpClient();
//连接超时
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
//请求超时
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
try {
// 获取HttpResponse实例
HttpResponse httpResp = httpClient.execute(httpPost);
// 判断是够请求成功
if (httpResp.getStatusLine().getStatusCode() == 200) {
// 获取返回的数据
result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
Logs.d("HttpPost success :");
Logs.d(result);
} else {
Logs.d("HttpPost failed" + " " + httpResp.getStatusLine().getStatusCode() + " " + EntityUtils.toString(httpResp.getEntity(), "UTF-8"));
result = "connect_failed";
}
} catch (ConnectTimeoutException e) {
result = "";
Logs.e("HttpPost overtime: " + "");
} catch (Exception e) {
e.printStackTrace();
Logs.e(e, "");
result = "";
}
return result;
}
use of org.apache.http.conn.ConnectTimeoutException in project saga-android by AnandChowdhary.
the class BasicNetwork method performRequest.
@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
long requestStart = SystemClock.elapsedRealtime();
while (true) {
HttpResponse httpResponse = null;
byte[] responseContents = null;
Map<String, String> responseHeaders = new HashMap<String, String>();
try {
// Gather headers.
Map<String, String> headers = new HashMap<String, String>();
addCacheHeaders(headers, request.getCacheEntry());
httpResponse = mHttpStack.performRequest(request, headers);
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
responseHeaders = convertHeaders(httpResponse.getAllHeaders());
// Handle cache validation.
if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, request.getCacheEntry().data, responseHeaders, true);
}
responseContents = entityToBytes(httpResponse.getEntity());
// if the request is slow, log it.
long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
logSlowRequests(requestLifetime, request, responseContents, statusLine);
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_NO_CONTENT) {
throw new IOException();
}
return new NetworkResponse(statusCode, responseContents, responseHeaders, false);
} catch (SocketTimeoutException e) {
attemptRetryOnException("socket", request, new TimeoutError());
} catch (ConnectTimeoutException e) {
attemptRetryOnException("connection", request, new TimeoutError());
} catch (MalformedURLException e) {
throw new RuntimeException("Bad URL " + request.getUrl(), e);
} catch (IOException e) {
int statusCode = 0;
NetworkResponse networkResponse = null;
if (httpResponse != null) {
statusCode = httpResponse.getStatusLine().getStatusCode();
} else {
if (request.getCacheEntry() != null && request.getCacheEntry().data != null) {
return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, request.getCacheEntry().data, responseHeaders, true);
} else {
throw new NoConnectionError(e);
}
}
VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
if (responseContents != null) {
networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false);
if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
} else {
// TODO: Only throw ServerError for 5xx status codes.
throw new ServerError(networkResponse);
}
} else {
throw new NetworkError(networkResponse);
}
}
}
}
Aggregations