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:org.dspace.submit.lookup.PubmedService.java
public List<Record> search(String query) throws IOException, HttpException { List<Record> results = new ArrayList<>(); if (!ConfigurationManager.getBooleanProperty(SubmissionLookupService.CFG_MODULE, "remoteservice.demo")) { HttpGet method = null;// www.jav a 2 s . co m try { HttpClient client = new DefaultHttpClient(); client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); URIBuilder uriBuilder = new URIBuilder("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi"); uriBuilder.addParameter("db", "pubmed"); uriBuilder.addParameter("datetype", "edat"); uriBuilder.addParameter("retmax", "10"); uriBuilder.addParameter("term", query); method = new HttpGet(uriBuilder.build()); // Execute the method. HttpResponse response = client.execute(method); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode != HttpStatus.SC_OK) { throw new RuntimeException("WS call failed: " + statusLine); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); Document inDoc = builder.parse(response.getEntity().getContent()); Element xmlRoot = inDoc.getDocumentElement(); Element idList = XMLUtils.getSingleElement(xmlRoot, "IdList"); List<String> pubmedIDs = XMLUtils.getElementValueList(idList, "Id"); results = getByPubmedIDs(pubmedIDs); } catch (ParserConfigurationException e1) { log.error(e1.getMessage(), e1); } catch (SAXException e1) { log.error(e1.getMessage(), e1); } } catch (Exception e1) { log.error(e1.getMessage(), e1); } finally { if (method != null) { method.releaseConnection(); } } } else { InputStream stream = null; try { File file = new File(ConfigurationManager.getProperty("dspace.dir") + "/config/crosswalks/demo/pubmed-search.xml"); stream = new FileInputStream(file); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document inDoc = builder.parse(stream); Element xmlRoot = inDoc.getDocumentElement(); Element idList = XMLUtils.getSingleElement(xmlRoot, "IdList"); List<String> pubmedIDs = XMLUtils.getElementValueList(idList, "Id"); results = getByPubmedIDs(pubmedIDs); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } } return results; }
From source file:gov.in.bloomington.georeporter.models.Open311.java
/** * Lazy load an Http client/*from w ww . j av a 2 s. co m*/ * * @return * DefaultHttpClient */ private static DefaultHttpClient getClient() { if (mClient == null) { mClient = new DefaultHttpClient(); mClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); mClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); mClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT); mClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT); } return mClient; }
From source file:org.jclouds.http.apachehc.config.ApacheHCHttpCommandExecutorServiceModule.java
@Singleton @Provides/*from w w w . j ava 2 s . c om*/ final HttpParams newBasicHttpParams(HttpUtils utils) { BasicHttpParams params = new BasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "jclouds/1.0"); if (utils.getConnectionTimeout() > 0) { params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, utils.getConnectionTimeout()); } if (utils.getSocketOpenTimeout() > 0) { params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, utils.getSocketOpenTimeout()); } if (utils.getMaxConnections() > 0) ConnManagerParams.setMaxTotalConnections(params, utils.getMaxConnections()); if (utils.getMaxConnectionsPerHost() > 0) { ConnPerRoute connectionsPerRoute = new ConnPerRouteBean(utils.getMaxConnectionsPerHost()); ConnManagerParams.setMaxConnectionsPerRoute(params, connectionsPerRoute); } HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); return params; }
From source file:org.onehippo.cms7.brokenlinks.LinkChecker.java
public LinkChecker(CheckExternalBrokenLinksConfig config, Session session) { this.session = session; ClientConnectionManager connManager = new PoolingClientConnectionManager(); HttpParams params = new SyncBasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout()); params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout()); params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false); params.setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, false); HttpClient client = null;/*from w w w . j av a2 s . com*/ try { final String httpClientClassName = config.getHttpClientClassName(); Class<? extends HttpClient> clientClass = (Class<? extends HttpClient>) Class .forName(httpClientClassName); final Constructor<? extends HttpClient> constructor = clientClass .getConstructor(ClientConnectionManager.class, HttpParams.class); client = constructor.newInstance(connManager, params); } catch (ClassNotFoundException e) { log.error("Could not find configured http client class", e); } catch (NoSuchMethodException e) { log.error("Could not find constructor of signature <init>(ClientConnectionmanager, HttpParams)", e); } catch (InvocationTargetException e) { log.error("Could not invoke constructor of httpClient", e); } catch (InstantiationException e) { log.error("Could not instantiate http client", e); } catch (IllegalAccessException e) { log.error("Not allowed to access http client constructor", e); } if (client == null) { client = new DefaultHttpClient(connManager, params); } httpClient = client; nrOfThreads = config.getNrOfHttpThreads(); // authentication preemptive true // allow circular redirects true }
From source file:cl.mmoscoso.geocomm.sync.GeoCommCreatePointAsyncTask.java
@Override protected Boolean doInBackground(Void... params) { // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpParams httpParams = httpclient.getParams(); httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000); HttpPost httppost = new HttpPost(this.hostname); //http://172.16.50.35/~ramirez/testAddPoint.php //http://172.16.57.132/~laost/Symfony/web/app_dev.php/addPoint/ try {/*from ww w . jav a2s . c o m*/ // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("name", this.name)); nameValuePairs.add(new BasicNameValuePair("description", this.desc)); nameValuePairs.add(new BasicNameValuePair("latitude", this.latitude)); nameValuePairs.add(new BasicNameValuePair("longitude", this.longitude)); nameValuePairs.add(new BasicNameValuePair("route", Integer.toString(this.id_route))); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); int responseCode = response.getStatusLine().getStatusCode(); Log.i(TAGNAME, "ERROR: " + responseCode); switch (responseCode) { default: Log.i(TAGNAME, "ERROR"); //Toast.makeText(this.context,R.string.error_not200code, Toast.LENGTH_SHORT).show(); break; case 200: HttpEntity entity = response.getEntity(); if (entity != null) { String responseBody = EntityUtils.toString(entity); //Log.i(TAGNAME, responseBody); JSONObject jObj, point; try { Log.i(TAGNAME, "tamao: " + responseBody); jObj = new JSONObject(responseBody); this.status = jObj.getInt("status"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } break; } } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } return true; }
From source file:com.bbxiaoqu.api.ApiAsyncTask.java
@Override protected Object doInBackground(Void... params) { if (!Utils.isNetworkAvailable(mContext)) { return TIMEOUT_ERROR; }//from ww w .j a v a 2s. c om String requestUrl = MarketAPI.API_URLS[mReuqestAction]; requestUrl = GETURL(requestUrl, mParameter);//?GETURL HttpEntity requestEntity = null; try { requestEntity = ApiRequestFactory.getRequestEntity(mReuqestAction, mParameter); } catch (UnsupportedEncodingException e) { Utils.D("OPPS...This device not support UTF8 encoding.[should not happend]"); return BUSSINESS_ERROR; } Object result = null; HttpResponse response = null; HttpUriRequest request = null; try { request = ApiRequestFactory.getRequest(requestUrl, mReuqestAction, requestEntity); mClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);// mClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);// response = mClient.execute(request); final int statusCode = response.getStatusLine().getStatusCode(); Utils.D("requestUrl " + requestUrl + " statusCode: " + statusCode); if (HttpStatus.SC_OK != statusCode) { // ? return statusCode; } result = ApiResponseFactory.getResponse(mContext, mReuqestAction, response); // ?API Response?BUSSINESS_ERROR?610 return result == null ? BUSSINESS_ERROR : result; } catch (IOException e) { Utils.D("Market API encounter the IO exception[mostly is timeout exception]", e); return TIMEOUT_ERROR; } finally { // release the connection if (request != null) { request.abort(); } if (response != null) { try { HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } } catch (IOException e) { Utils.D("release low-level resource error"); } } } }
From source file:org.lol.reddit.account.RedditAccount.java
public static LoginResultPair login(final Context context, final String username, final String password, final HttpClient client) { 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);//w w w .j a v a 2s.co m 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:cn.jachohx.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(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 . j a v a 2s. c o m connectionManager = new ThreadSafeClientConnManager(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() { 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; } } } } }); }
From source file:cl.mmoscoso.geocomm.sync.GeoCommGetRoutesOwnerAsyncTask.java
@Override protected Boolean doInBackground(String... params) { // TODO Auto-generated method stub HttpClient httpclient = new DefaultHttpClient(); HttpParams httpParams = httpclient.getParams(); httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000); HttpPost httppost = new HttpPost(this.hostname); Log.i(TAGNAME, "Try to connect to " + this.hostname); try {//from ww w . java2 s . c o m List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("id", Integer.toString(this.id_user))); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); Log.i(TAGNAME, "Post Request"); HttpResponse response = httpclient.execute(httppost); int responseCode = response.getStatusLine().getStatusCode(); switch (responseCode) { default: Toast.makeText(this.context, R.string.error_not200code, Toast.LENGTH_SHORT).show(); break; case 200: HttpEntity entity = response.getEntity(); if (entity != null) { String responseBody = EntityUtils.toString(entity); //Log.i(TAGNAME, responseBody); JSONObject jObj, ruta; try { Log.i(TAGNAME, "Reading JSONResponse"); jObj = new JSONObject(responseBody); SharedPreferences preferences = this.context.getSharedPreferences("userInformation", context.MODE_PRIVATE); Boolean is_allroutes = preferences.getBoolean("is_allroutes", false); for (int i = 0; i < jObj.length(); i++) { ruta = new JSONObject(jObj.getString(jObj.names().getString(i))); if (is_allroutes) { if (ruta.getBoolean("public") == false) { list_routes.add(new GeoCommRoute(ruta.getString("name"), ruta.getString("owner"), ruta.getInt("id"), ruta.getInt("totalPoints"), ruta.getString("description"), ruta.getBoolean("public"))); } } else list_routes.add(new GeoCommRoute(ruta.getString("name"), ruta.getString("owner"), ruta.getInt("id"), ruta.getInt("totalPoints"), ruta.getString("description"), ruta.getBoolean("public"))); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } break; } } catch (ClientProtocolException e) { // TODO Auto-generated catch block Log.e(TAGNAME, e.toString()); return false; } catch (IOException e) { // TODO Auto-generated catch block Log.e(TAGNAME, e.toString()); return false; } return true; }
From source file:edu.hust.grid.crawl.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(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); params.setParameter("http.language.Accept-Language", "en-us"); params.setParameter("http.protocol.content-charset", "UTF-8"); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); if (config.isIncludeHttpsPages()) { schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); }/* ww w .j a v a 2s. c om*/ connectionManager = new ThreadSafeClientConnManager(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.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0"); } 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(); }