List of usage examples for org.apache.http.params CoreConnectionPNames SO_TIMEOUT
String SO_TIMEOUT
To view the source code for org.apache.http.params CoreConnectionPNames SO_TIMEOUT.
Click Source Link
From source file:com.ryan.ryanreader.account.RedditAccount.java
public static LoginResultPair login(final Context context, final String username, final String password, final HttpClient client) { // ???//from w w w . j av a 2 s . c om final ArrayList<NameValuePair> fields = new ArrayList<NameValuePair>(3); fields.add(new BasicNameValuePair("user", username)); fields.add(new BasicNameValuePair("passwd", password)); fields.add(new BasicNameValuePair("api_type", "json")); // TODO put somewhere else final HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.USER_AGENT, Constants.ua(context)); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000); // TODO // remove // hardcoded // params, // put // in // network // prefs params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000); params.setParameter(CoreConnectionPNames.MAX_HEADER_COUNT, 100); params.setParameter(ClientPNames.HANDLE_REDIRECTS, true); params.setParameter(ClientPNames.MAX_REDIRECTS, 5); final HttpPost request = new HttpPost("https://ssl.reddit.com/api/login"); request.setParams(params); try { request.setEntity(new UrlEncodedFormEntity(fields, HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { return new LoginResultPair(LoginResult.INTERNAL_ERROR); } final PersistentCookieStore cookies = new PersistentCookieStore(); final HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookies); final StatusLine status; final HttpEntity entity; try { final HttpResponse response = client.execute(request, localContext); status = response.getStatusLine(); entity = response.getEntity(); } catch (IOException e) { return new LoginResultPair(LoginResult.CONNECTION_ERROR); } if (status.getStatusCode() != 200) { return new LoginResultPair(LoginResult.REQUEST_ERROR); } final JsonValue result; try { result = new JsonValue(entity.getContent()); result.buildInThisThread(); } catch (IOException e) { return new LoginResultPair(LoginResult.CONNECTION_ERROR); } final String modhash; try { // TODO use the more general reddit error finder final JsonBufferedArray errors = result.asObject().getObject("json").getArray("errors"); errors.join(); if (errors.getCurrentItemCount() != 0) { for (final JsonValue v : errors) { for (final JsonValue s : v.asArray()) { // TODO handle unknown messages by concatenating all // Reddit's strings if (s.getType() == JsonValue.Type.STRING) { Log.i("RR DEBUG ERROR", s.asString()); // lol, reddit api if (s.asString().equalsIgnoreCase("WRONG_PASSWORD") || s.asString().equalsIgnoreCase("invalid password") || s.asString().equalsIgnoreCase("passwd")) return new LoginResultPair(LoginResult.WRONG_PASSWORD); if (s.asString().contains("too much")) // also // "RATELIMIT", // but // that's // not as // descriptive return new LoginResultPair(LoginResult.RATELIMIT, s.asString()); } } } return new LoginResultPair(LoginResult.UNKNOWN_REDDIT_ERROR); } final JsonBufferedObject data = result.asObject().getObject("json").getObject("data"); modhash = data.getString("modhash"); } catch (NullPointerException e) { return new LoginResultPair(LoginResult.JSON_ERROR); } catch (InterruptedException e) { return new LoginResultPair(LoginResult.JSON_ERROR); } catch (IOException e) { return new LoginResultPair(LoginResult.JSON_ERROR); } return new LoginResultPair(LoginResult.SUCCESS, new RedditAccount(username, modhash, cookies, 0), null); }
From source file:com.autonomousturk.crawler.fetcher.PageFetcher.java
public PageFetcher(CrawlConfig config) { super(config); HttpParams params = new BasicHttpParams(); HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params); paramsBean.setVersion(HttpVersion.HTTP_1_1); paramsBean.setContentCharset("UTF-8"); paramsBean.setUseExpectContinue(false); params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgentString()); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout()); params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout()); params.setBooleanParameter("http.protocol.handle-redirects", false); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); if (config.isIncludeHttpsPages()) { schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); }//from w w w . ja v a 2 s. co m connectionManager = new PoolingClientConnectionManager(schemeRegistry); connectionManager.setMaxTotal(config.getMaxTotalConnections()); connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost()); httpClient = new DefaultHttpClient(connectionManager, params); if (config.getProxyHost() != null) { if (config.getProxyUsername() != null) { httpClient.getCredentialsProvider().setCredentials( new AuthScope(config.getProxyHost(), config.getProxyPort()), new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword())); } HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort()); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); Header contentEncoding = entity.getContentEncoding(); if (contentEncoding != null) { HeaderElement[] codecs = contentEncoding.getElements(); for (HeaderElement codec : codecs) { if (codec.getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } }); if (connectionMonitorThread == null) { connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager); } connectionMonitorThread.start(); }
From source file:org.sbs.goodcrawler.fetcher.PageFetcher.java
public PageFetcher(FetchConfig config) { super(config); HttpParams params = new BasicHttpParams(); HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params); paramsBean.setVersion(HttpVersion.HTTP_1_1); paramsBean.setContentCharset("UTF-8"); paramsBean.setUseExpectContinue(false); params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); params.setParameter(CoreProtocolPNames.USER_AGENT, config.getAgent()); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeoutMilliseconds()); params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout()); params.setBooleanParameter("http.protocol.handle-redirects", false); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); if (config.isHttps()) { schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); }// w w w . j a v a 2 s .c o m connectionManager = new PoolingClientConnectionManager(schemeRegistry); connectionManager.setMaxTotal(config.getMaxTotalConnections()); connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost()); httpClient = new DefaultHttpClient(connectionManager, params); if (config.getProxyHost() != null) { if (config.getProxyUsername() != null) { httpClient.getCredentialsProvider().setCredentials( new AuthScope(config.getProxyHost(), config.getProxyPort()), new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword())); } HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort()); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); Header contentEncoding = entity.getContentEncoding(); if (contentEncoding != null) { HeaderElement[] codecs = contentEncoding.getElements(); for (HeaderElement codec : codecs) { if (codec.getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } }); if (connectionMonitorThread == null) { connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager); } connectionMonitorThread.start(); }
From source file:com.github.seratch.signedrequest4j.SignedRequestApacheHCImpl.java
@Override public HttpResponse doRequest(String url, HttpMethod method, RequestBody body, String charset) throws IOException { HttpClient httpClient = new DefaultHttpClient(); HttpUriRequest request = getRequest(method, url); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeoutMillis); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeoutMillis); httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT); httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, charset); for (String name : headersToOverwrite.keySet()) { request.setHeader(name, headersToOverwrite.get(name)); }//from w w w . ja va2s . c om String oAuthNonce = String.valueOf(new SecureRandom().nextLong()); Long oAuthTimestamp = System.currentTimeMillis() / 1000; String signature = getSignature(url, method, oAuthNonce, oAuthTimestamp); String authorizationHeader = getAuthorizationHeader(signature, oAuthNonce, oAuthTimestamp); request.setHeader("Authorization", authorizationHeader); if (method == HttpMethod.POST) { HttpPost postRequest = (HttpPost) request; BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(new ByteArrayInputStream(body.getBody())); entity.setContentType(body.getContentType()); postRequest.setEntity(entity); } else if (method == HttpMethod.PUT) { HttpPut putRequest = (HttpPut) request; BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(new ByteArrayInputStream(body.getBody())); entity.setContentType(body.getContentType()); putRequest.setEntity(entity); } org.apache.http.HttpResponse apacheHCResponse = httpClient.execute(request); if (apacheHCResponse.getStatusLine().getStatusCode() >= 400) { HttpResponse httpResponse = toReturnValue(apacheHCResponse, charset); throw new HttpException(apacheHCResponse.getStatusLine().getReasonPhrase(), httpResponse); } return toReturnValue(apacheHCResponse, charset); }
From source file:com.appdynamics.openstack.nova.RestClient.java
static HttpClient httpClientWithTrustManager() throws KeyManagementException, NoSuchAlgorithmException { HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); httpClient.getParams().setParameter("http.connection-manager.max-per-host", 1); X509TrustManager tm = new X509TrustManager() { @Override// ww w. ja v a 2 s .c o m public X509Certificate[] getAcceptedIssuers() { // TODO Auto-generated method stub return null; } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } }; SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx); ClientConnectionManager ccm = httpClient.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", ssf, 443)); // Scheme("https", ssf, 443)); return new DefaultHttpClient(ccm, httpClient.getParams()); }
From source file:com.almende.eve.transport.http.ApacheHttpClient.java
/** * Instantiates a new apache http client. * *//*from w w w .j a va 2s . c o m*/ private ApacheHttpClient() { // Allow self-signed SSL certificates: final TrustStrategy trustStrategy = new TrustSelfSignedStrategy(); final X509HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier(); final SchemeRegistry schemeRegistry = SchemeRegistryFactory.createDefault(); SSLSocketFactory sslSf; try { sslSf = new SSLSocketFactory(trustStrategy, hostnameVerifier); final Scheme https = new Scheme("https", 443, sslSf); schemeRegistry.register(https); } catch (Exception e) { LOG.warning("Couldn't init SSL socket, https not supported!"); } // Work with PoolingClientConnectionManager final ClientConnectionManager connection = new PoolingClientConnectionManager(schemeRegistry); // Provide eviction thread to clear out stale threads. new Thread(new Runnable() { @Override public void run() { try { while (true) { synchronized (this) { wait(5000); connection.closeExpiredConnections(); connection.closeIdleConnections(30, TimeUnit.SECONDS); } } } catch (final InterruptedException ex) { } } }).start(); // generate httpclient httpClient = new DefaultHttpClient(connection); // Set cookie policy and persistent cookieStore try { httpClient.setCookieStore(new MyCookieStore()); } catch (final Exception e) { LOG.log(Level.WARNING, "Failed to initialize persistent cookieStore!", e); } final HttpParams params = httpClient.getParams(); params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000); params.setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false); params.setParameter(CoreConnectionPNames.TCP_NODELAY, true); httpClient.setParams(params); }
From source file:com.wrapp.android.webimage.ImageDownloader.java
public static Date getServerTimestamp(final URL imageUrl) { Date expirationDate = new Date(); try {/*from ww w . jav a2 s . co m*/ final String imageUrlString = imageUrl.toString(); if (imageUrlString == null || imageUrlString.length() == 0) { throw new Exception("Passed empty URL"); } LogWrapper.logMessage("Requesting image '" + imageUrlString + "'"); final HttpClient httpClient = new DefaultHttpClient(); final HttpParams httpParams = httpClient.getParams(); httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, CONNECTION_TIMEOUT_IN_MS); httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT_IN_MS); httpParams.setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, DEFAULT_BUFFER_SIZE); final HttpHead httpHead = new HttpHead(imageUrlString); final HttpResponse response = httpClient.execute(httpHead); Header[] header = response.getHeaders("Expires"); if (header != null && header.length > 0) { SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US); expirationDate = dateFormat.parse(header[0].getValue()); LogWrapper .logMessage("Image at " + imageUrl.toString() + " expires on " + expirationDate.toString()); } } catch (Exception e) { LogWrapper.logException(e); } return expirationDate; }
From source file:com.nanocrawler.fetcher.PageFetcher.java
public PageFetcher(CrawlConfig config) { this.config = config; HttpParams params = new BasicHttpParams(); HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params); paramsBean.setVersion(HttpVersion.HTTP_1_1); paramsBean.setContentCharset("UTF-8"); paramsBean.setUseExpectContinue(false); params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgentString()); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout()); params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout()); params.setBooleanParameter("http.protocol.handle-redirects", false); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); if (config.isIncludeHttpsPages()) { schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); }// w w w. ja v a 2s . c o m connectionManager = new PoolingClientConnectionManager(schemeRegistry); connectionManager.setMaxTotal(config.getMaxTotalConnections()); connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost()); httpClient = new DefaultHttpClient(connectionManager, params); }
From source file:com.android.picasaphotouploader.ImageUploader.java
/** * Upload image to Picasa/* ww w.j av a 2s. co m*/ */ public void run() { // create items for http client UploadNotification notification = new UploadNotification(context, item.imageId, item.imageSize, item.imageName); String url = "http://picasaweb.google.com/data/feed/api/user/" + item.prefs.getString("email", "") + "/albumid/" + item.prefs.getString("album", ""); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); try { // new file and and entity File file = new File(item.imagePath); Multipart multipart = new Multipart("Media multipart posting", "END_OF_PART"); // create entity parts multipart.addPart("<entry xmlns='http://www.w3.org/2005/Atom'><title>" + item.imageName + "</title><category scheme=\"http://schemas.google.com/g/2005#kind\" term=\"http://schemas.google.com/photos/2007#photo\"/></entry>", "application/atom+xml"); multipart.addPart(file, item.imageType); // create new Multipart entity MultipartNotificationEntity entity = new MultipartNotificationEntity(multipart, notification); // get http params HttpParams params = client.getParams(); // set protocal and timeout for httpclient params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(15000)); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(15000)); // set body with upload entity post.setEntity(entity); // set headers post.addHeader("Authorization", "GoogleLogin auth=" + item.imageAuth); post.addHeader("GData-Version", "2"); post.addHeader("MIME-version", "1.0"); // execute upload to picasa and get response and status HttpResponse response = client.execute(post); StatusLine line = response.getStatusLine(); // return code indicates upload failed so throw exception if (line.getStatusCode() > 201) { throw new Exception("Failed upload"); } // shut down connection client.getConnectionManager().shutdown(); // notify user that file has been uploaded notification.finished(); } catch (Exception e) { // file upload failed so abort post and close connection post.abort(); client.getConnectionManager().shutdown(); // get user preferences and number of retries for failed upload SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); int maxRetries = Integer.valueOf(prefs.getString("retries", "").substring(1)); // check if we can connect to internet and if we still have any tries left // to try upload again if (CheckInternet.getInstance().canConnect(context, prefs) && retries < maxRetries) { // remove notification for failed upload and queue item again notification.remove(); queue.execute(new ImageUploader(context, queue, item, retries++)); } else { // upload failed, so let's notify user notification.failed(); } } }
From source file:org.eclipse.ecf.internal.provider.filetransfer.httpclient4.ECFHttpClientProtocolSocketFactory.java
public Socket connectSocket(final Socket sock, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { int timeout = params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0); Trace.entering(Activator.PLUGIN_ID, DebugOptions.METHODS_ENTERING, ECFHttpClientProtocolSocketFactory.class, "connectSocket " + remoteAddress.toString() + " timeout=" + timeout); //$NON-NLS-1$ //$NON-NLS-2$ try {/*from w ww.ja va2s . c o m*/ // Use String.valueOf to protect against null Trace.trace(Activator.PLUGIN_ID, "bind(" + String.valueOf(localAddress) + ")"); //$NON-NLS-1$//$NON-NLS-2$ sock.bind(localAddress); Trace.trace(Activator.PLUGIN_ID, "connect(" + remoteAddress.toString() + ", " + timeout + ")"); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ sock.connect(remoteAddress, timeout); Trace.trace(Activator.PLUGIN_ID, "connected"); //$NON-NLS-1$ } catch (IOException e) { Trace.catching(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_CATCHING, ECFHttpClientProtocolSocketFactory.class, "createSocket", e); //$NON-NLS-1$ fireEvent(socketConnectListener, new SocketClosedEvent(source, sock, sock)); Trace.throwing(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_THROWING, ECFHttpClientProtocolSocketFactory.class, "createSocket", e); //$NON-NLS-1$ throw e; } Socket toReturn; Socket wrapped = new CloseMonitoringSocket(sock, socketConnectListener, source); SocketConnectedEvent connectedEvent = new SocketConnectedEvent(source, sock, wrapped); fireEvent(socketConnectListener, connectedEvent); // Change the wrapped socket if one of the receivers of the SocketConnectedEvent changed it if (connectedEvent.getSocket() != wrapped) { toReturn = connectedEvent.getSocket(); ((CloseMonitoringSocket) wrapped).setWrappedSocket(toReturn); } else { toReturn = wrapped; } return toReturn; }