List of usage examples for org.apache.http.params CoreConnectionPNames CONNECTION_TIMEOUT
String CONNECTION_TIMEOUT
To view the source code for org.apache.http.params CoreConnectionPNames CONNECTION_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 ww . j a v a 2 s.c o m*/ 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.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 ww . ja v a 2 s.co m*/ connectionManager = new PoolingClientConnectionManager(schemeRegistry); connectionManager.setMaxTotal(config.getMaxTotalConnections()); connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost()); httpClient = new DefaultHttpClient(connectionManager, params); }
From source file:com.wrapp.android.webimage.ImageDownloader.java
public static Date getServerTimestamp(final URL imageUrl) { Date expirationDate = new Date(); try {//from w ww . j a v a2s.c o 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.android.picasaphotouploader.ImageUploader.java
/** * Upload image to Picasa// ww w . j av a2s . c o 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:uk.co.visalia.brightpearl.apiclient.http.httpclient4.HttpClient4ClientFactory.java
private void createClient() { BasicHttpParams httpParams = new BasicHttpParams(); httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeoutMs); httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeoutMs); HttpClientParams.setRedirecting(httpParams, allowRedirects); HttpClientParams.setConnectionManagerTimeout(httpParams, connectionManagerTimeoutMs); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(schemeRegistry); connectionManager.setMaxTotal(maxConnections); connectionManager.setDefaultMaxPerRoute(maxConnectionsPerRoute); DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpParams); this.client = new HttpClient4Client(httpClient); }
From source file:com.investoday.code.util.aliyun.api.gateway.util.HttpUtil.java
/** * HTTP POST?//from ww w. ja v a2 s.c om * * @param url http://host+path+query * @param headers Http * @param formParam ?? * @param appKey APP KEY * @param appSecret APP * @param timeout * @param signHeaderPrefixList ???Header? * @return * @throws Exception */ public static HttpResponse httpPost(String url, Map<String, String> headers, Map<String, String> formParam, String appKey, String appSecret, int timeout, List<String> signHeaderPrefixList) throws Exception { if (headers == null) { headers = new HashMap<String, String>(); } headers.put(HttpHeader.HTTP_HEADER_CONTENT_TYPE, ContentType.CONTENT_TYPE_FORM); headers = initialBasicHeader(headers, appKey, appSecret, HttpMethod.POST, url, formParam, signHeaderPrefixList); HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(timeout)); HttpPost post = new HttpPost(url); for (Map.Entry<String, String> e : headers.entrySet()) { post.addHeader(e.getKey(), e.getValue()); } UrlEncodedFormEntity formEntity = buildFormEntity(formParam); if (formEntity != null) { post.setEntity(formEntity); } return httpClient.execute(post); }
From source file:NioHttpClient.java
public NioHttpClient(String user_agent, HttpRequestExecutionHandler request_handler, EventListener connection_listener) throws Exception { // Construct the long-lived HTTP parameters. HttpParams parameters = new BasicHttpParams(); parameters/* w w w. ja v a 2 s .com*/ // Socket data timeout is 5,000 milliseconds (5 seconds). .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) // Maximum time allowed for connection establishment is 10,00 milliseconds (10 seconds). .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000) // Socket buffer size is 8 kB. .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) // Don't bother to check for stale TCP connections. .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) // Don't use Nagle's algorithm (in other words minimize latency). .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) // Set the user agent string that the client sends to the server. .setParameter(CoreProtocolPNames.USER_AGENT, user_agent); // Construct the core HTTP request processor. BasicHttpProcessor http_processor = new BasicHttpProcessor(); // Add Content-Length header to request where appropriate. http_processor.addInterceptor(new RequestContent()); // Always include Host header in requests. http_processor.addInterceptor(new RequestTargetHost()); // Maintain connection keep-alive by default. http_processor.addInterceptor(new RequestConnControl()); // Include user agent information in each request. http_processor.addInterceptor(new RequestUserAgent()); // Allocate an HTTP client handler. BufferingHttpClientHandler client_handler = new BufferingHttpClientHandler(http_processor, // Basic HTTP Processor. request_handler, new DefaultConnectionReuseStrategy(), parameters); client_handler.setEventListener(connection_listener); // Use two worker threads for the IO reactor. io_reactor = new DefaultConnectingIOReactor(2, parameters); io_event_dispatch = new DefaultClientIOEventDispatch(client_handler, parameters); }
From source file:net.oauth.client.httpclient4.HttpClient4.java
public HttpResponseMessage execute(HttpMessage request, Map<String, Object> parameters) throws IOException { final String method = request.method; final String url = request.url.toExternalForm(); final InputStream body = request.getBody(); final boolean isDelete = DELETE.equalsIgnoreCase(method); final boolean isPost = POST.equalsIgnoreCase(method); final boolean isPut = PUT.equalsIgnoreCase(method); byte[] excerpt = null; HttpRequestBase httpRequest;//from w w w .j a va2 s . c o m if (isPost || isPut) { HttpEntityEnclosingRequestBase entityEnclosingMethod = isPost ? new HttpPost(url) : new HttpPut(url); if (body != null) { ExcerptInputStream e = new ExcerptInputStream(body); excerpt = e.getExcerpt(); String length = request.removeHeaders(HttpMessage.CONTENT_LENGTH); entityEnclosingMethod .setEntity(new InputStreamEntity(e, (length == null) ? -1 : Long.parseLong(length))); } httpRequest = entityEnclosingMethod; } else if (isDelete) { httpRequest = new HttpDelete(url); } else { httpRequest = new HttpGet(url); } for (Map.Entry<String, String> header : request.headers) { httpRequest.addHeader(header.getKey(), header.getValue()); } HttpParams params = httpRequest.getParams(); for (Map.Entry<String, Object> p : parameters.entrySet()) { String name = p.getKey(); String value = p.getValue().toString(); if (FOLLOW_REDIRECTS.equals(name)) { params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.parseBoolean(value)); } else if (READ_TIMEOUT.equals(name)) { params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, Integer.parseInt(value)); } else if (CONNECT_TIMEOUT.equals(name)) { params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, Integer.parseInt(value)); } } HttpClient client = clientPool.getHttpClient(new URL(httpRequest.getURI().toString())); HttpResponse httpResponse = client.execute(httpRequest); return new HttpMethodResponse(httpRequest, httpResponse, excerpt, request.getContentCharset()); }
From source file:palamarchuk.fraudguide.utils.QueryMaster.java
@Override public void run() { super.run();/*from w w w . ja va 2s . c o m*/ if (!isNetworkConnected()) { handler.sendEmptyMessage(QUERY_MASTER_NETWORK_ERROR); return; } HttpParams httpParams = new BasicHttpParams(); httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeoutConnection); DefaultHttpClient httpclient = new DefaultHttpClient(httpParams); // httpclient.setParams(httpParams); HttpPost httpPost; HttpGet httpGet; HttpResponse response = null; try { if (queryType == QUERY_GET) { httpGet = new HttpGet(url); response = httpclient.execute(httpGet); } else if (queryType == QUERY_POST) { httpPost = new HttpPost(url); if (entity != null) { httpPost.setEntity(entity); } response = httpclient.execute(httpPost); } serverResponse = EntityUtils.toString(response.getEntity()); handler.sendEmptyMessage(QUERY_MASTER_COMPLETE); } catch (ClientProtocolException e) { e.printStackTrace(); handler.sendEmptyMessage(QUERY_MASTER_ERROR); } catch (IOException e) { e.printStackTrace(); handler.sendEmptyMessage(QUERY_MASTER_ERROR); } catch (NullPointerException e) { e.printStackTrace(); handler.sendEmptyMessage(QUERY_MASTER_ERROR); } }