List of usage examples for org.apache.http.client.utils URLEncodedUtils format
public static String format(final Iterable<? extends NameValuePair> parameters, final Charset charset)
From source file:com.francisli.processing.http.HttpClient.java
/** * Performs a GET request to fetch content from the specified path with * the specified parameters. The parameters are assembled into a query * string and appended to the path./*from w w w .j a va2 s. com*/ * * @param params String: a collection of parameters to pass as a query string with the path */ public HttpRequest GET(String path, Map params) { //// clean up path a little bit- remove whitespace, add slash prefix path = path.trim(); if (!path.startsWith("/")) { path = "/" + path; } //// if params passed, format into a query string and append if (params != null) { ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>(); for (Object key : params.keySet()) { Object value = params.get(key); pairs.add(new BasicNameValuePair(key.toString(), value.toString())); } String queryString = URLEncodedUtils.format(pairs, HTTP.UTF_8); if (path.contains("?")) { path = path + "&" + queryString; } else { path = path + "?" + queryString; } } //// finally, invoke request HttpGet get = new HttpGet(getHost().toURI() + path); if (useOAuth) { OAuthConsumer consumer = new CommonsHttpOAuthConsumer(oauthConsumerKey, oauthConsumerSecret); consumer.setTokenWithSecret(oauthAccessToken, oauthAccessTokenSecret); try { consumer.sign(get); } catch (Exception e) { System.err.println("HttpClient: Unable to sign GET request for OAuth"); } } HttpRequest request = new HttpRequest(this, getHost(), get); request.start(); return request; }
From source file:org.mobicents.servlet.sip.restcomm.interpreter.RcmlInterpreter.java
public void load(final URI uri, final String method, List<NameValuePair> parameters) throws InterpreterException { final List<State> possibleStates = new ArrayList<State>(); possibleStates.add(IDLE);/*from ww w .j a va 2 s. co m*/ possibleStates.add(EXECUTING); assertState(possibleStates); // Load the XML resource for execution. HttpRequestDescriptor request = null; try { request = new HttpRequestDescriptor(uri, method, parameters); } catch (final UnsupportedEncodingException ignored) { } catch (final URISyntaxException exception) { save(notify(context, Notification.ERROR, 11100)); throw new InterpreterException(exception); } resourceUri = request.getUri(); requestMethod = request.getMethod(); requestParameters = URLEncodedUtils.format(request.getParameters(), "UTF-8"); try { final HttpRequestExecutor executor = new HttpRequestExecutor(); final HttpResponseDescriptor response = executor.execute(request); responseHeaders = HttpUtils.toString(response.getHeaders()); if (HttpStatus.SC_OK == response.getStatusCode() && (response.getContentLength() > 0 || response.isChunked())) { final String contentType = response.getContentType(); if (contentType.contains("text/xml") || contentType.contains("application/xml") || contentType.contains("text/html")) { final String data = StringUtils.toString(response.getContent()); responseBody = data; resource = resourceBuilder.build(data); } else if (contentType.contains("audio/wav") || contentType.contains("audio/wave") || contentType.contains("audio/x-wav")) { resource = resourceBuilder.build(loadWav(response.getContent())); } else if (contentType.contains("text/plain")) { final String data = StringUtils.toString(response.getContent()); responseBody = data; resource = resourceBuilder.build(loadPlainText(data)); } else { save(notify(context, Notification.ERROR, 12300)); throw new InterpreterException("Invalid content type " + contentType); } if (!"Response".equals(resource.getName())) { save(notify(context, Notification.ERROR, 12102)); throw new InterpreterException( "Invalid document root for document located @ " + request.getUri().toString()); } } else { save(notify(context, Notification.ERROR, 11200)); throw new InterpreterException("Received an unsucessful response when requesting a document @ " + request.getUri().toString()); } } catch (final IOException exception) { save(notify(context, Notification.ERROR, 11200)); throw new InterpreterException(exception); } catch (final RcmlDocumentBuilderException exception) { save(notify(context, Notification.ERROR, 12100)); throw new InterpreterException(exception); } catch (final URISyntaxException exception) { save(notify(context, Notification.ERROR, 11100)); throw new InterpreterException(exception); } }
From source file:com.sababado.network.AsyncServiceCallTask.java
@Override protected Bundle doInBackground(Void... args) { mRunning = true;//from w w w. j av a2s . c om log(LOG_TYPE_DEBUG, "****in AsyncServiceCallTask do in Background"); int attempts = 0; if (!UtilNetwork.isNetworkAvailable(mContext)) { Bundle responseBundle = new Bundle(); responseBundle.putString(EXTRA_ERR_MSG, "Sorry, there is limited or no connectivity. Please try again later."); responseBundle.putInt(EXTRA_ERR_CODE, ERR_CODE_NO_NETWORK); return responseBundle; } //get names and values String[] paramNames = mService.getAllParamNames(); String[] paramValues = mService.getAllParamValues(); //build parameter list String paramString = ""; if (paramNames != null && paramNames.length > 0) { try { //this assumes there is a 1 to 1 number of names and values List<NameValuePair> nvPairs = new LinkedList<NameValuePair>(); for (int i = 0; i < paramNames.length; i++) { nvPairs.add(new BasicNameValuePair(paramNames[i], paramValues[i])); } paramString = URLEncodedUtils.format(nvPairs, "utf-8"); } catch (ArrayIndexOutOfBoundsException e) { String message = "Failed paring param names and values (Index out of bounds). Make sure the there are the same number of param names and values."; log(LOG_TYPE_ERROR, message); throw new ArrayIndexOutOfBoundsException(message); } } String url = mService.getUrl(); //format the url string if (paramString.length() > 0) { //format url to have parameters only if there are parameters to add. if (!url.endsWith("?")) url += "?"; url += paramString; } log(LOG_TYPE_DEBUG, "Url: " + url); HttpResponse response = null; //while under the maximum number of attempts... while (attempts < MAX_ATTEMPTS) { try { log(LOG_TYPE_DEBUG, (attempts + 1) + "/" + MAX_ATTEMPTS + ": Creating Http Client"); //create the HttpClient HttpClient client = new DefaultHttpClient(); //set the request switch (mService.getCallType()) { case Service.CALL_TYPE_GET: log(LOG_TYPE_DEBUG, "Making GET Call"); HttpGet getRequest = new HttpGet(url); response = client.execute(getRequest); break; case Service.CALL_TYPE_POST: log(LOG_TYPE_DEBUG, "Making POST Call"); HttpPost postRequest = new HttpPost(url); response = client.execute(postRequest); break; case Service.CALL_TYPE_PUT: log(LOG_TYPE_DEBUG, "Making PUT Call"); HttpPut putRequest = new HttpPut(url); response = client.execute(putRequest); break; case Service.CALL_TYPE_DELETE: log(LOG_TYPE_DEBUG, "Making DELETE Call"); HttpDelete deleteRequest = new HttpDelete(url); response = client.execute(deleteRequest); break; default: throw new RuntimeException( "Invalid Call type, please see Service.CALL_TYPE_* for possible types."); } } catch (IOException e) { attempts++; publishProgress("IOException: Retrying, attempt " + (attempts + 1), e.getMessage()); } if (response != null) break; } //check if exceeded max number of attempts if (attempts == MAX_ATTEMPTS) { //max number of attempts exceeded, error Bundle responseBundle = new Bundle(); //responseBundle.putString(EXTRA_ERR_MSG, "Failed "+MAX_ATTEMPTS+" attempts, please retry later."); responseBundle.putString(EXTRA_ERR_MSG, "Could not connect to the server, please try again later"); responseBundle.putInt(EXTRA_ERR_CODE, ERR_CODE_MAX_ATTEMPTS_REACHED); return responseBundle; } return parseResponse(response); }
From source file:com.uwindsor.elgg.project.http.RequestParams.java
protected String getParamString() { return URLEncodedUtils.format(getParamsList(), ENCODING); }
From source file:com.scottjjohnson.finance.analysis.YahooFinanceClient.java
/** * Builds a url for extracting historical quotes data from Yahoo Finance. * //from w w w .ja v a 2 s .co m * The date range ends on the Friday prior to the current date and begins DateRangeInDays days earlier. * * @param ticker * stock ticker symbol to be queried * @param dateRangeInDays * number of calendar days of history to be retrieved * @return url containing a YQL query string */ private String buildHistoricalDataURL(String ticker, int dateRangeInDays) { Calendar cal = DateUtils.getStockExchangeCalendar(); // today // ************* HOKEY WORKAROUND FOR YAHOO ISSUE -- Ask for extra day into future to bust cache cal.add(Calendar.DAY_OF_WEEK, 1); dateRangeInDays++; // ************* Date endDate = cal.getTime(); cal.add(Calendar.DAY_OF_WEEK, -dateRangeInDays); Date startDate = cal.getTime(); // SimpleDateFormat is not thread-safe so creating one as needed. SimpleDateFormat yqlDateFormat = new SimpleDateFormat("yyyy-MM-dd"); String query = String.format(HISTORICAL_DATA_QUERY_PATTERN, ticker, yqlDateFormat.format(startDate), yqlDateFormat.format(endDate)); List<NameValuePair> queryParams = new ArrayList<NameValuePair>(); queryParams.add(new BasicNameValuePair("q", query)); queryParams.add(new BasicNameValuePair("format", RESPONSE_FORMAT)); queryParams.add(new BasicNameValuePair("env", DATA_SOURCE_ENV)); StringBuilder sb = new StringBuilder(BASE_URL); sb.append(URLEncodedUtils.format(queryParams, "UTF-8")); LOGGER.debug("YQL query = {}.", sb.toString()); return sb.toString(); }
From source file:com.digitalpebble.stormcrawler.filtering.basic.BasicURLNormalizer.java
/** * Basic filter to remove query parameters from urls so parameters that * don't change the content of the page can be removed. An example would be * a google analytics query parameter like "utm_campaign" which might have * several different values for a url that points to the same content. *///from w ww .jav a 2s. c o m private String filterQueryElements(String urlToFilter) { try { // Handle illegal characters by making a url first // this will clean illegal characters like | URL url = new URL(urlToFilter); if (StringUtils.isEmpty(url.getQuery())) { return urlToFilter; } List<NameValuePair> pairs = new ArrayList<>(); URLEncodedUtils.parse(pairs, new Scanner(url.getQuery()), "UTF-8"); Iterator<NameValuePair> pairsIterator = pairs.iterator(); while (pairsIterator.hasNext()) { NameValuePair param = pairsIterator.next(); if (queryElementsToRemove.contains(param.getName())) { pairsIterator.remove(); } } StringBuilder newFile = new StringBuilder(); if (url.getPath() != null) { newFile.append(url.getPath()); } if (!pairs.isEmpty()) { Collections.sort(pairs, comp); String newQueryString = URLEncodedUtils.format(pairs, StandardCharsets.UTF_8); newFile.append('?').append(newQueryString); } if (url.getRef() != null) { newFile.append('#').append(url.getRef()); } return new URL(url.getProtocol(), url.getHost(), url.getPort(), newFile.toString()).toString(); } catch (MalformedURLException e) { LOG.warn("Invalid urlToFilter {}. {}", urlToFilter, e); return null; } }
From source file:org.mahasen.util.PutUtil.java
/** * @param file/*from w w w . j av a 2 s .co m*/ * @throws InterruptedException * @throws RegistryException * @throws PastException * @throws IOException */ public void secureUpload(File file, Id resourceId) throws InterruptedException, RegistryException, PastException, IOException, MahasenConfigurationException, MahasenException { // get the IP addresses pool to upload files. Vector<String> nodeIpsToPut = getNodeIpsToPut(); MahasenFileSplitter mahasenFileSplitter = new MahasenFileSplitter(); mahasenFileSplitter.split(file); HashMap<String, String> fileParts = mahasenFileSplitter.getPartNames(); mahasenResource.addPartNames(fileParts.keySet().toArray(new String[fileParts.size()])); Random random = new Random(); for (String currentPartName : fileParts.keySet()) { File splittedFilePart = new File(fileParts.get(currentPartName)); int randomNumber = random.nextInt(nodeIpsToPut.size()); String nodeIp = nodeIpsToPut.get(randomNumber); try { setTrustStore(); URI uri = null; ArrayList<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("splittedfilename", splittedFilePart.getName())); uri = URIUtils.createURI("https", nodeIp + ":" + MahasenConstants.SERVER_PORT, -1, "/mahasen/upload_request_ajaxprocessor.jsp", URLEncodedUtils.format(qparams, "UTF-8"), null); MahasenUploadWorker uploadWorker = new MahasenUploadWorker(uri, currentPartName, splittedFilePart, mahasenResource, nodeIp); uploadThread = new Thread(uploadWorker); uploadWorker.setJobId(jobId); //keep track of uploading parts AtomicInteger noOfParts = new AtomicInteger(0); storedNoOfParts.put(jobId, noOfParts); uploadThread.start(); } catch (Exception e) { e.printStackTrace(); } } final BlockFlag blockFlag = new BlockFlag(true, 6000); while (true) { AtomicInteger noOfParts = storedNoOfParts.get(jobId); if (noOfParts.get() == fileParts.size()) { storedNoOfParts.remove(uploadThread.getId()); System.out.println("uploaded no of parts " + noOfParts + "out of " + fileParts.size() + "going out " + "#####Thread id:" + uploadThread.getId()); blockFlag.unblock(); break; } if (blockFlag.isBlocked()) { mahasenManager.getNode().getEnvironment().getTimeSource().sleep(10); } else { throw new MahasenException("Time out in uploading " + file.getName()); } } mahasenManager.insertIntoDHT(resourceId, mahasenResource, false); mahasenManager.insertTreeMapIntoDHT(resourceId, mahasenResource, false); ReplicateRequestStarter replicateStarter = new ReplicateRequestStarter(mahasenResource); Thread replicateThread = new Thread(replicateStarter); replicateThread.start(); }
From source file:mobisocial.musubi.identity.AphidIdentityProvider.java
public boolean initiateTwoPhaseClaim(IBIdentity ident, String key, int requestId) { // Send the request to Aphid HttpClient http = new CertifiedHttpClient(mContext); List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("req", new Integer(requestId).toString())); qparams.add(new BasicNameValuePair("type", new Integer(ident.authority_.ordinal()).toString())); qparams.add(new BasicNameValuePair("uid", ident.principal_)); qparams.add(new BasicNameValuePair("time", new Long(ident.temporalFrame_).toString())); qparams.add(new BasicNameValuePair("key", key)); try {//w w w .j a va2 s .c o m // Send the request URI uri = URIUtils.createURI(URL_SCHEME, SERVER_LOCATION, -1, CLAIM_PATH, URLEncodedUtils.format(qparams, "UTF-8"), null); Log.d(TAG, "Aphid URI: " + uri.toString()); HttpGet httpGet = new HttpGet(uri); HttpResponse response = http.execute(httpGet); int code = response.getStatusLine().getStatusCode(); // Read the response BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String responseStr = ""; String line = ""; while ((line = rd.readLine()) != null) { responseStr += line; } Log.d(TAG, "Server response:" + responseStr); // Only 200 should indicate that this worked if (code == HttpURLConnection.HTTP_OK) { // Mark as notified (suppress repeated texts) MIdentity mid = mIdentitiesManager.getIdentityForIBHashedIdentity(ident); if (mid != null) { MPendingIdentity pendingIdent = mPendingIdentityManager.lookupIdentity(mid.id_, ident.temporalFrame_, requestId); if (pendingIdent == null) { pendingIdent = mPendingIdentityManager.fillPendingIdentity(mid.id_, ident.temporalFrame_); mPendingIdentityManager.insertIdentity(pendingIdent); } pendingIdent.notified_ = true; mPendingIdentityManager.updateIdentity(pendingIdent); } return true; } } catch (URISyntaxException e) { Log.e(TAG, "URISyntaxException", e); } catch (IOException e) { Log.i(TAG, "Error claiming keys."); } return false; }
From source file:eu.masconsult.bgbanking.banks.dskbank.DskClient.java
@Override public List<RawBankAccount> getBankAccounts(String authToken) throws IOException, ParseException, AuthenticationException { String uri = BASE_URL + "?" + URLEncodedUtils.format( Arrays.asList(new BasicNameValuePair(XML_ID, LIST_ACCOUNTS_XML_ID)), ENCODING) + "&" + authToken; // Get the accounts list Log.i(TAG, "Getting from: " + uri); final HttpGet get = new HttpGet(uri); get.setHeader("Accept", "*/*"); DefaultHttpClient httpClient = getHttpClient(); Log.v(TAG, "sending " + get.toString()); final HttpResponse resp = httpClient.execute(get); if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new ParseException("getBankAccounts: unhandled http status " + resp.getStatusLine().getStatusCode() + " " + resp.getStatusLine().getReasonPhrase()); }//from ww w . jav a 2 s .c o m HttpEntity entity = resp.getEntity(); Document doc = Jsoup.parse(entity.getContent(), "utf-8", BASE_URL); if (!checkLoggedIn(doc)) { throw new AuthenticationException("session expired!"); } Element content = doc.getElementById("PageContent"); if (content == null) { throw new ParseException("getBankAccounts: can't find PageContent"); } Elements tables = content.getElementsByTag("table"); if (tables == null || tables.size() == 0) { throw new ParseException("getBankAccounts: can't find table in PageContent"); } Elements rows = tables.first().getElementsByTag("tr"); if (rows == null || rows.size() == 0) { throw new ParseException("getBankAccounts: first table is empty in PageContent"); } ArrayList<RawBankAccount> bankAccounts = new ArrayList<RawBankAccount>(rows.size()); String lastCurrency = null; for (Element row : rows) { RawBankAccount bankAccount = obtainBankAccountFromHtmlTableRow(row); if (bankAccount != null) { if (bankAccount.getCurrency() == null) { bankAccount.setCurrency(lastCurrency); } else { lastCurrency = bankAccount.getCurrency(); } bankAccounts.add(bankAccount); } } return bankAccounts; }
From source file:fr.shywim.antoinedaniel.utils.Utils.java
public static boolean getInformationFromCdn(Context context, String soundname, String page, boolean force) { List<NameValuePair> nameValuePairs = new ArrayList<>(1); nameValuePairs.add(new BasicNameValuePair("sound_id", soundname)); nameValuePairs.add(new BasicNameValuePair("page", page)); String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8"); String url = context.getResources().getString(R.string.api_get_one_sound) + '?' + paramString; final HttpClient httpclient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try {/*ww w .j a va 2s . co m*/ HttpResponse response = httpclient.execute(httpGet); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String result = EntityUtils.toString(response.getEntity()); JSONObject jo = new JSONObject(result); if (!prepareDownloadFromCdn(context, jo.getString("soundname"), jo.getString("imagename"), jo.getString("description"), jo.getString("link"), Integer.parseInt(jo.getString("version")), force)) { return false; } else jo.getString("version"); } } catch (IOException | JSONException e) { Crashlytics.logException(e); } return true; }