List of usage examples for org.apache.http.client HttpClient getParams
@Deprecated HttpParams getParams();
From source file:org.jboss.aerogear.windows.mpns.MpnsServiceBuilder.java
/** * Returns a fully initialized instance of {@link MpnsService}, * according to the requested settings./* www . j a v a 2 s . c om*/ * * @return a new instance of MpnsService */ public MpnsService build() { checkInitialization(); // Client Configuration HttpClient client; if (httpClient != null) { client = httpClient; } else if (pooledMax == 1) { client = new DefaultHttpClient(); } else { client = new DefaultHttpClient(Utilities.poolManager(pooledMax)); } if (proxy != null) { client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } if (securityInfo != null) { try { KeyStore keyStore; if (securityInfo.getProvider() == null) { keyStore = KeyStore.getInstance(securityInfo.getName()); } else { keyStore = KeyStore.getInstance(securityInfo.getName(), securityInfo.getProvider()); } keyStore.load(new ByteArrayInputStream(securityInfo.getCert()), securityInfo.getPassword().toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keyStore, securityInfo.getPassword().toCharArray()); KeyManager[] km = kmfactory.getKeyManagers(); // create SSL socket factory SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(km, null, null); org.apache.http.conn.ssl.SSLSocketFactory sslSocketFactory = new org.apache.http.conn.ssl.SSLSocketFactory( sslContext); Scheme https = new Scheme("https", 443, sslSocketFactory); client.getConnectionManager().getSchemeRegistry().register(https); } catch (Exception e) { throw new IllegalArgumentException(e); } } if (timeout > 0) { HttpParams params = client.getParams(); HttpConnectionParams.setConnectionTimeout(params, timeout); HttpConnectionParams.setSoTimeout(params, timeout); } // Configure service AbstractMpnsService service; if (pooledMax == 1) { service = new MpnsServiceImpl(client, delegate); } else { service = new MpnsPooledService(client, executor, delegate); } if (isQueued) { service = new MpnsQueuedService(service); } service.start(); return service; }
From source file:pam.widget.activities.EntityBoardActivity.java
private EntityBoard getEntityBoardFromApi(Bundle extras) { HttpClient httpclient = new DefaultHttpClient(); String myVersion = "0.0"; PackageManager manager = getBaseContext().getPackageManager(); try {// ww w . ja va 2 s .co m myVersion = (manager.getPackageInfo(getBaseContext().getPackageName(), 0).versionName); } catch (NameNotFoundException e) { e.printStackTrace(); } httpclient.getParams().setParameter("http.useragent", "PamelaWidget " + myVersion + " for Android - " + System.getProperty("http.agent")); String url = extras.getString("URL") + "?lang=" + getString(R.string.lang); // Prepare a request object HttpGet httpget = new HttpGet(url.replace(" ", "%20")); Log.i("", url); // Execute the request HttpResponse response; JSONArray json = new JSONArray(); Date currentDate = new Date(); String space = extras.getString("Name"); ArrayList<Entity> entities = new ArrayList<Entity>(); try { response = httpclient.execute(httpget); HttpEntity httpEntity = response.getEntity(); if (httpEntity != null) { // A Simple JSON Response Read InputStream instream = httpEntity.getContent(); String result = convertStreamToString(instream); json = new JSONArray(result); instream.close(); } for (int i = 0; i < json.length(); ++i) { String rawName = json.getString(i); String displayName = rawName; Type type = Type.UNKNOWN; String customType = ""; if (rawName.split(":").length != 6) { if (rawName.indexOf("(") != -1 && rawName.indexOf(")") > rawName.indexOf("(")) { type = Type.DEVICE; customType = rawName.substring(rawName.indexOf("(") + 1, rawName.indexOf(")")); customType = customType.substring(0, 1).toUpperCase() + customType.substring(1); displayName = rawName.substring(0, rawName.indexOf("(")); } else { type = Type.PERSON; } } Entity entity = new Entity(displayName, type, Status.ACTIVE); if (customType != "") { entity.setCustomType(customType); } entities.add(entity); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } ArrayList<Entity> orderedEntities = new ArrayList<Entity>(); int peopleAmount = this.addEntitiesOfType(entities, orderedEntities, Type.PERSON); this.addEntitiesOfType(entities, orderedEntities, Type.DEVICE); int unknownAmount = this.addEntitiesOfType(entities, orderedEntities, Type.UNKNOWN); Boolean spaceIsOpen = peopleAmount > 0 || unknownAmount > 0; space = space + " (" + getString(spaceIsOpen ? R.string.open : R.string.closed) + ")"; return new EntityBoard(currentDate, space, orderedEntities); }
From source file:com.ucai.test.control.DeviceControlActivity.java
private int sendDataByPost(MedicalData data) { if (null == data) { return 0; }/*from w ww . jav a 2 s . c om*/ boolean DEBUG_SWL = true; if (DEBUG_SWL) { Log.i(TAG, "run--------sendDataByPost----------");//post??? } JSONObject obj = transToJson(data);//??json? HttpResponse httpResponse = null; HttpPost httpPost = new HttpPost(Constant.URL_USER_DATA); HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000); // client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 3000); //? try { httpPost.setEntity(new StringEntity(obj.toString())); httpResponse = new DefaultHttpClient().execute(httpPost); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } if (null == httpResponse) { // Toast.makeText(this, "", Toast.LENGTH_SHORT).show(); return -1; // } if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { if (DEBUG_SWL) { Log.i(TAG, "httpResponse.getStatusLine().getStatusCode() == 200"); } try { String result = EntityUtils.toString(httpResponse.getEntity()); if (DEBUG_SWL) { Log.i(TAG, "result---------------" + result); } } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return 1; //post? } else { return 2; //post } }
From source file:andlabs.lounge.lobby.util.parser.PlayParser.java
private InputStream downloadStream(String url) { InputStream inputStream = null; HttpClient client = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(url); HttpResponse response = null;//from w w w . jav a 2 s .com if (url == null) { return null; } HttpParams clientParams = client.getParams(); HttpConnectionParams.setConnectionTimeout(clientParams, CONNECT_TIMEOUT); HttpConnectionParams.setSoTimeout(clientParams, CONNECT_TIMEOUT); try { response = client.execute(getRequest); HttpEntity entity = response.getEntity(); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode == 200 && entity != null) { inputStream = response.getEntity().getContent(); return inputStream; } } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.lyncode.xoai.serviceprovider.iterators.SetIterator.java
private void harvest() throws InternalHarvestException, NoRecordsMatchException, BadResumptionTokenException, NoSetHierarchyException {/*w w w .j a v a2 s. c o m*/ HttpClient httpclient = new DefaultHttpClient(); String url = makeUrl(); log.info("Harvesting: " + url); HttpGet httpget = new HttpGet(url); httpget.addHeader("User-Agent", HarvesterManager.USERAGENT); httpget.addHeader("From", HarvesterManager.FROM); HttpResponse response = null; if (this.proxyIp != null && this.proxyPort > -1) { HttpHost proxy = new HttpHost(this.proxyIp, this.proxyPort); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } try { response = httpclient.execute(httpget); StatusLine status = response.getStatusLine(); log.debug(response.getStatusLine()); if (status.getStatusCode() == 503) // 503 Status (must wait) { org.apache.http.Header[] headers = response.getAllHeaders(); for (org.apache.http.Header h : headers) { if (h.getName().equals("Retry-After")) { String retry_time = h.getValue(); try { Thread.sleep(Integer.parseInt(retry_time) * 1000); } catch (NumberFormatException e) { log.warn("Cannot parse " + retry_time + " to Integer", e); } catch (InterruptedException e) { log.debug(e.getMessage(), e); } httpclient.getConnectionManager().shutdown(); httpclient = new DefaultHttpClient(); response = httpclient.execute(httpget); } } } HttpEntity entity = response.getEntity(); InputStream instream = entity.getContent(); Document doc = XMLUtils.parseDocument(instream); XMLUtils.checkListSets(doc); NodeList listSets = doc.getElementsByTagName("set"); for (int i = 0; i < listSets.getLength(); i++) _queue.add(XMLUtils.getSet(listSets.item(i))); resumption = XMLUtils.getText(doc.getElementsByTagName("resumptionToken")); log.debug("RESUMPTION: " + resumption); } catch (IOException e) { throw new InternalHarvestException(e); } catch (ParserConfigurationException e) { throw new InternalHarvestException(e); } catch (SAXException e) { throw new InternalHarvestException(e); } }
From source file:org.openrepose.core.services.httpclient.impl.HttpConnectionPoolServiceImpl.java
@Override public HttpClientResponse getClient(String clientId) throws HttpClientNotFoundException { if (poolMap.isEmpty()) { defaultClientId = DEFAULT_POOL_ID; HttpClient httpClient = clientGenerator(DEFAULT_POOL); poolMap.put(defaultClientId, httpClient); }/*from www.j a v a 2 s .co m*/ if (clientId != null && !clientId.isEmpty() && !isAvailable(clientId)) { HttpClient httpClient = clientGenerator(DEFAULT_POOL); poolMap.put(clientId, httpClient); } final HttpClient requestedClient; if (clientId == null || clientId.isEmpty()) { requestedClient = poolMap.get(defaultClientId); } else { if (isAvailable(clientId)) { requestedClient = poolMap.get(clientId); } else { throw new HttpClientNotFoundException("Pool " + clientId + "not available"); } } String clientInstanceId = requestedClient.getParams().getParameter(CLIENT_INSTANCE_ID).toString(); String userId = httpClientUserManager.addUser(clientInstanceId); PoolStats poolStats = ((PoolingClientConnectionManager) requestedClient.getConnectionManager()) .getTotalStats(); LOG.trace("Client requested, pool currently leased: {}, available: {}, pending: {}, max: {}", poolStats.getLeased(), poolStats.getAvailable(), poolStats.getPending(), poolStats.getMax()); return new HttpClientResponseImpl(requestedClient, clientId, clientInstanceId, userId); }
From source file:com.lyncode.xoai.serviceprovider.iterators.RecordIterator.java
private void harvest() throws NoRecordsMatchException, BadResumptionTokenException, CannotDisseminateFormatException, NoSetHierarchyException, InternalHarvestException { HttpClient httpclient = new DefaultHttpClient(); String url = makeUrl();/*from www . j av a 2 s .co m*/ log.info("Harvesting: " + url); HttpGet httpget = new HttpGet(url); httpget.addHeader("User-Agent", HarvesterManager.USERAGENT); httpget.addHeader("From", HarvesterManager.FROM); HttpResponse response = null; if (this.proxyIp != null && this.proxyPort > -1) { HttpHost proxy = new HttpHost(this.proxyIp, this.proxyPort); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } try { response = httpclient.execute(httpget); StatusLine status = response.getStatusLine(); log.debug(response.getStatusLine()); if (status.getStatusCode() == 503) // 503 Status (must wait) { org.apache.http.Header[] headers = response.getAllHeaders(); for (org.apache.http.Header h : headers) { if (h.getName().equals("Retry-After")) { String retry_time = h.getValue(); try { Thread.sleep(Integer.parseInt(retry_time) * 1000); } catch (NumberFormatException e) { log.warn("Cannot parse " + retry_time + " to Integer", e); } catch (InterruptedException e) { log.debug(e.getMessage(), e); } httpclient.getConnectionManager().shutdown(); httpclient = new DefaultHttpClient(); response = httpclient.execute(httpget); } } } HttpEntity entity = response.getEntity(); InputStream instream = entity.getContent(); Document doc = XMLUtils.parseDocument(instream); XMLUtils.checkListRecords(doc); NodeList listRecords = doc.getElementsByTagName("record"); for (int i = 0; i < listRecords.getLength(); i++) _queue.add(XMLUtils.getRecord(listRecords.item(i))); resumption = XMLUtils.getText(doc.getElementsByTagName("resumptionToken")); log.debug("RESUMPTION: " + resumption); } catch (IOException e) { throw new InternalHarvestException(e); } catch (ParserConfigurationException e) { throw new InternalHarvestException(e); } catch (SAXException e) { throw new InternalHarvestException(e); } }
From source file:com.lyncode.xoai.serviceprovider.iterators.IdentifierIterator.java
private void harvest() throws InternalHarvestException, NoRecordsMatchException, BadResumptionTokenException, CannotDisseminateFormatException, NoSetHierarchyException { HttpClient httpclient = new DefaultHttpClient(); String url = makeUrl();/*from w w w . j ava 2s . c o m*/ log.info("Harvesting: " + url); HttpGet httpget = new HttpGet(url); httpget.addHeader("User-Agent", HarvesterManager.USERAGENT); httpget.addHeader("From", HarvesterManager.FROM); HttpResponse response = null; if (this.proxyIp != null && this.proxyPort > -1) { HttpHost proxy = new HttpHost(this.proxyIp, this.proxyPort); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } try { response = httpclient.execute(httpget); StatusLine status = response.getStatusLine(); log.debug(response.getStatusLine()); if (status.getStatusCode() == 503) // 503 Status (must wait) { org.apache.http.Header[] headers = response.getAllHeaders(); for (org.apache.http.Header h : headers) { if (h.getName().equals("Retry-After")) { String retry_time = h.getValue(); try { Thread.sleep(Integer.parseInt(retry_time) * 1000); } catch (NumberFormatException e) { log.warn("Cannot parse " + retry_time + " to Integer", e); } catch (InterruptedException e) { log.debug(e.getMessage(), e); } httpclient.getConnectionManager().shutdown(); httpclient = new DefaultHttpClient(); response = httpclient.execute(httpget); } } } HttpEntity entity = response.getEntity(); InputStream instream = entity.getContent(); Document doc = XMLUtils.parseDocument(instream); XMLUtils.checkListIdentifiers(doc); NodeList listRecords = doc.getElementsByTagName("header"); for (int i = 0; i < listRecords.getLength(); i++) _queue.add(XMLUtils.getIdentifier(listRecords.item(i))); resumption = XMLUtils.getText(doc.getElementsByTagName("resumptionToken")); log.debug("RESUMPTION: " + resumption); } catch (IOException e) { throw new InternalHarvestException(e); } catch (ParserConfigurationException e) { throw new InternalHarvestException(e); } catch (SAXException e) { throw new InternalHarvestException(e); } }
From source file:ti.modules.titanium.geolocation.GeolocationModule.java
@Override public boolean handleMessage(final Message msg) { if (msg.what == MSG_LOOKUP) { AsyncTask<Object, Void, Integer> task = new AsyncTask<Object, Void, Integer>() { @Override// w ww.j a v a2 s. c om protected Integer doInBackground(Object... args) { try { String url = (String) args[0]; String direction = (String) args[1]; KrollCallback callback = (KrollCallback) args[2]; if (DBG) { Log.d(LCAT, "GEO URL: " + url); } HttpGet httpGet = new HttpGet(url); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 5000); // TODO use property // HttpConnectionParams.setSoTimeout(httpParams, 15000); // //TODO use property HttpClient client = new DefaultHttpClient(httpParams); ResponseHandler<String> responseHandler = new BasicResponseHandler(); client.getParams().setBooleanParameter("http.protocol.expect-continue", false); String response = client.execute(httpGet, responseHandler); if (DBG) { Log.i(LCAT, "Received Geo: " + response); } KrollDict event = null; if (response != null) { try { JSONObject r = new JSONObject(response); if (r.getBoolean("success")) { if (direction.equals("r")) { event = buildReverseResponse(r); } else { event = buildForwardResponse(r); } } else { event = new KrollDict(); KrollDict err = new KrollDict(); String errorCode = r.getString("errorcode"); err.put("message", "Unable to resolve message: Code (" + errorCode + ")"); err.put("code", errorCode); event.put("error", err); } } catch (JSONException e) { Log.e(LCAT, "Error converting geo response to JSONObject: " + e.getMessage(), e); } } if (event != null) { event.put("source", this); callback.callAsync(event); } } catch (Throwable t) { Log.e(LCAT, "Error retrieving geocode information: " + t.getMessage(), t); } return -1; } }; task.execute(msg.getData().getString("url"), msg.getData().getString("direction"), msg.obj); return true; } return super.handleMessage(msg); }
From source file:com.poomoo.edao.activity.UploadPicsActivity.java
private void upload(File file) { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(eDaoClientConfig.imageurl); // ?Post?,Post client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, eDaoClientConfig.timeout); client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, eDaoClientConfig.timeout); MultipartEntity entity = new MultipartEntity(); // , // List<File> list = new ArrayList<File>(); // // File/* ww w .j a v a 2 s . c om*/ // list.add(file1); // list.add(file2); // list.add(file3); // list.add(file4); // System.out.println("list.size():" + list.size()); // for (int i = 0; i < list.size(); i++) { // ContentBody body = new FileBody(list.get(i)); // entity.addPart("file", body); // ??? // } System.out.println( "upload" + "uploadCount" + ":" + uploadCount + "filelist.size" + ":" + filelist.size()); entity.addPart("file", new FileBody(file)); post.setEntity(entity); // ?Post? Message message = new Message(); try { entity.addPart("imageType", new StringBody(String.valueOf(uploadCount + 1), Charset.forName("utf-8"))); entity.addPart("userId", new StringBody(userId, Charset.forName("utf-8"))); HttpResponse response; response = client.execute(post); // Post if (response.getStatusLine().getStatusCode() == 200) { uploadCount++; message.what = 1; } else message.what = 2; // return EntityUtils.toString(response.getEntity(), "UTF-8"); // // ?? } catch (Exception e) { // TODO ? catch ? e.printStackTrace(); message.what = 2; System.out.println("IOException:" + e.getMessage()); } finally { client.getConnectionManager().shutdown(); // ? myHandler.sendMessage(message); } }