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:org.jongo.mocks.JongoClient.java
private JongoResponse doRequest(final String url, final List<NameValuePair> parameters) { final String urlParameters = URLEncodedUtils.format(parameters, "UTF-8"); JongoResponse response = null;/*from ww w .j a va 2 s.c om*/ try { HttpURLConnection con = (HttpURLConnection) new URL(jongoUrl + url).openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Accept", MediaType.APPLICATION_XML); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); con.setDoOutput(true); con.setDoInput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); BufferedReader r = null; if (con.getResponseCode() != Response.Status.CREATED.getStatusCode()) { r = new BufferedReader(new InputStreamReader(con.getErrorStream())); } else { r = new BufferedReader(new InputStreamReader(con.getInputStream())); } StringBuilder rawresponse = new StringBuilder(); String strLine = null; while ((strLine = r.readLine()) != null) { rawresponse.append(strLine); rawresponse.append("\n"); } try { response = XmlXstreamTest.successFromXML(rawresponse.toString()); } catch (Exception e) { response = XmlXstreamTest.errorFromXML(rawresponse.toString()); } } catch (Exception ex) { ex.printStackTrace(); } return response; }
From source file:eu.masconsult.bgbanking.banks.dskbank.DskClient.java
@Override public String authenticate(String username, String password) throws IOException, ParseException, CaptchaException { final HttpResponse resp; final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_USERNAME, username)); params.add(new BasicNameValuePair(PARAM_PASSWORD, password)); final HttpEntity entity; try {// ww w .j av a 2 s . c om entity = new UrlEncodedFormEntity(params); } catch (final UnsupportedEncodingException e) { // this should never happen. throw new IllegalStateException(e); } String uri = BASE_URL + "?" + URLEncodedUtils.format(Arrays.asList(new BasicNameValuePair(XML_ID, AUTH_XML_ID)), ENCODING); Log.i(TAG, "Authenticating to: " + uri); final HttpPost post = new HttpPost(uri); post.addHeader(entity.getContentType()); post.setHeader("Accept", "*/*"); post.setEntity(entity); try { resp = getHttpClient().execute(post); if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new ParseException("login: unhandled http status " + resp.getStatusLine().getStatusCode() + " " + resp.getStatusLine().getReasonPhrase()); } String response = EntityUtils.toString(resp.getEntity()); Log.v(TAG, "response = " + response); Document doc = Jsoup.parse(response, BASE_URL); Element mainForm = doc.getElementById("mainForm"); if (mainForm == null) { throw new ParseException("login: missing mainForm"); } String action = BASE_URL + mainForm.attr("action"); Log.v(TAG, "action=" + action); UrlQuerySanitizer sanitizer = new UrlQuerySanitizer(action); String user_id = sanitizer.getValue(PARAM_USER_ID); String session_id = sanitizer.getValue(PARAM_SESSION_ID); if (user_id == null || "".equals(user_id) || session_id == null || "".equals(session_id)) { if (doc.getElementsByClass("redtext").size() > 0) { // bad authentication return null; } else { // TODO handle captcha Elements captcha = doc.select("input[name=captcha_hkey]"); if (captcha != null && captcha.size() == 1) { String captchaHash = captcha.first().attr("value"); String captchaUri = BASE_URL + "?" + URLEncodedUtils .format(Arrays.asList(new BasicNameValuePair(XML_ID, CAPTCHA_XML_ID), new BasicNameValuePair("captcha_key", captchaHash)), ENCODING); throw new CaptchaException(captchaUri); } throw new ParseException("no user_id or session_id: " + action); } } return URLEncodedUtils.format(Arrays.asList(new BasicNameValuePair(PARAM_USER_ID, user_id), new BasicNameValuePair(PARAM_SESSION_ID, session_id)), ENCODING); } catch (ClientProtocolException e) { throw new IOException(e.getMessage()); } }
From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.RMWebAppFilter.java
@Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { response.setCharacterEncoding("UTF-8"); String htmlEscapedUri = HtmlQuoting.quoteHtmlChars(request.getRequestURI()); if (htmlEscapedUri == null) { htmlEscapedUri = "/"; }//from w w w. j a v a 2 s.c om String uriWithQueryString = htmlEscapedUri; String htmlEscapedUriWithQueryString = htmlEscapedUri; String queryString = request.getQueryString(); if (queryString != null && !queryString.isEmpty()) { String reqEncoding = request.getCharacterEncoding(); if (reqEncoding == null || reqEncoding.isEmpty()) { reqEncoding = "ISO-8859-1"; } Charset encoding = Charset.forName(reqEncoding); List<NameValuePair> params = URLEncodedUtils.parse(queryString, encoding); String urlEncodedQueryString = URLEncodedUtils.format(params, encoding); uriWithQueryString += "?" + urlEncodedQueryString; htmlEscapedUriWithQueryString = HtmlQuoting .quoteHtmlChars(request.getRequestURI() + "?" + urlEncodedQueryString); } RMWebApp rmWebApp = injector.getInstance(RMWebApp.class); rmWebApp.checkIfStandbyRM(); if (rmWebApp.isStandby() && shouldRedirect(rmWebApp, htmlEscapedUri)) { String redirectPath = rmWebApp.getRedirectPath(); if (redirectPath != null && !redirectPath.isEmpty()) { redirectPath += uriWithQueryString; String redirectMsg = "This is standby RM. The redirect url is: " + htmlEscapedUriWithQueryString; PrintWriter out = response.getWriter(); out.println(redirectMsg); response.setHeader("Location", redirectPath); response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); return; } else { boolean doRetry = true; String retryIntervalStr = request.getParameter(YarnWebParams.NEXT_REFRESH_INTERVAL); int retryInterval = 0; if (retryIntervalStr != null) { try { retryInterval = Integer.parseInt(retryIntervalStr.trim()); } catch (NumberFormatException ex) { doRetry = false; } } int next = calculateExponentialTime(retryInterval); String redirectUrl = appendOrReplaceParamter(path + uriWithQueryString, YarnWebParams.NEXT_REFRESH_INTERVAL + "=" + (retryInterval + 1)); if (redirectUrl == null || next > MAX_SLEEP_TIME) { doRetry = false; } String redirectMsg = doRetry ? "Can not find any active RM. Will retry in next " + next + " seconds." : "There is no active RM right now."; redirectMsg += "\nHA Zookeeper Connection State: " + rmWebApp.getHAZookeeperConnectionState(); PrintWriter out = response.getWriter(); out.println(redirectMsg); if (doRetry) { response.setHeader("Refresh", next + ";url=" + redirectUrl); response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); } } return; } else if (ahsEnabled) { String ahsRedirectUrl = ahsRedirectPath(uriWithQueryString, rmWebApp); if (ahsRedirectUrl != null) { response.setHeader("Location", ahsRedirectUrl); response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); return; } } super.doFilter(request, response, chain); }
From source file:ch.uzh.ifi.attempto.ape.APEWebservice.java
/** * We create an HTTP GET query from the given parameters. If it turns out to be * too long (which we expect to happen very infrequently) then we fall back to creating * HTTP POST.//from ww w .ja v a 2 s .c o m * <p/> * BUG: Old versions of the SWI-Prolog HTTP server do not handle POST queries correctly. * Hopefully this has been fixed in v5.11.9 (but I haven't tested it). * See the bug report in the SWI-Prolog mailing list in 2010-11-03. * * @param nvps List of name-value pairs * @return HTTP request (either GET or POST) */ private HttpUriRequest getHttpUriRequest(List<NameValuePair> nvps) { String getQuery = wsUrl + "?" + URLEncodedUtils.format(nvps, HTTP.UTF_8); if (getQuery.length() > MAX_HTTP_GET_LENGTH) { HttpPost httppost = new HttpPost(wsUrl); try { httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { // BUG: Assuming that this cannot happen } return httppost; } return new HttpGet(getQuery); }
From source file:org.sakaiproject.shortenedurl.impl.BitlyUrlService.java
/** * Make a GET request and append the Map of parameters onto the query string. * @param address the fully qualified URL to make the request to * @param parameters the Map of parameters, ie key,value pairs * @return//from w ww . j av a 2 s. co m */ private String doGet(String address, Map<String, String> parameters) { try { List<NameValuePair> queryParams = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : parameters.entrySet()) { queryParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } URI uri = URIUtils.createURI(null, address, -1, null, URLEncodedUtils.format(queryParams, "UTF-8"), null); log.info(uri.toString()); return doGet(uri.toString()); } catch (URISyntaxException e) { log.error(e.getClass() + ":" + e.getMessage()); } return null; }
From source file:com.csipsimple.plugins.twvoip.CallHandler.java
@Override public void onReceive(Context context, Intent intent) { if (ACTION_GET_PHONE_HANDLERS.equals(intent.getAction())) { PendingIntent pendingIntent = null; // Extract infos from intent received String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); // Extract infos from settings SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String user = prefs.getString(CallHandlerConfig.KEY_12VOIP_USER, ""); String pwd = prefs.getString(CallHandlerConfig.KEY_12VOIP_PWD, ""); String nbr = prefs.getString(CallHandlerConfig.KEY_12VOIP_NBR, ""); // We must handle that clean way cause when call just to // get the row in account list expect this to reply correctly if (!TextUtils.isEmpty(number) && !TextUtils.isEmpty(user) && !TextUtils.isEmpty(nbr) && !TextUtils.isEmpty(pwd)) { // Build pending intent Intent i = new Intent(ACTION_DO_TWVOIP_CALL); i.setClass(context, getClass()); i.putExtra(Intent.EXTRA_PHONE_NUMBER, number); pendingIntent = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); // = PendingIntent.getActivity(context, 0, i, 0); }//from w ww.j a v a 2s . c o m // Build icon Bitmap bmp = null; Drawable icon = context.getResources().getDrawable(R.drawable.icon); BitmapDrawable bd = ((BitmapDrawable) icon); bmp = bd.getBitmap(); // Build the result for the row (label, icon, pending intent, and // excluded phone number) Bundle results = getResultExtras(true); if (pendingIntent != null) { results.putParcelable(Intent.EXTRA_REMOTE_INTENT_TOKEN, pendingIntent); } results.putString(Intent.EXTRA_TITLE, "12voip WebCallback"); if (bmp != null) { results.putParcelable(Intent.EXTRA_SHORTCUT_ICON, bmp); } // DO *NOT* exclude from next tel: intent cause we use a http method // results.putString(Intent.EXTRA_PHONE_NUMBER, number); } else if (ACTION_DO_TWVOIP_CALL.equals(intent.getAction())) { // Extract infos from intent received String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); // Extract infos from settings SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String user = prefs.getString(CallHandlerConfig.KEY_12VOIP_USER, ""); String pwd = prefs.getString(CallHandlerConfig.KEY_12VOIP_PWD, ""); String nbr = prefs.getString(CallHandlerConfig.KEY_12VOIP_NBR, ""); // params List<NameValuePair> params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("username", user)); params.add(new BasicNameValuePair("password", pwd)); params.add(new BasicNameValuePair("from", nbr)); params.add(new BasicNameValuePair("to", number)); String paramString = URLEncodedUtils.format(params, "utf-8"); String requestURL = "https://www.12voip.com//myaccount/makecall.php?" + paramString; HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(requestURL); // Create a response handler HttpResponse httpResponse; try { httpResponse = httpClient.execute(httpGet); Log.d(THIS_FILE, "response code is " + httpResponse.getStatusLine().getStatusCode()); if (httpResponse.getStatusLine().getStatusCode() == 200) { InputStreamReader isr = new InputStreamReader(httpResponse.getEntity().getContent()); BufferedReader br = new BufferedReader(isr); String line; String fullReply = ""; boolean foundSuccess = false; while ((line = br.readLine()) != null) { if (!TextUtils.isEmpty(line) && line.toLowerCase().contains("success")) { showToaster(context, "Success... wait a while you'll called back"); foundSuccess = true; break; } if (!TextUtils.isEmpty(line)) { fullReply = fullReply.concat(line); } } if (!foundSuccess) { showToaster(context, "Error : server error : " + fullReply); } } else { showToaster(context, "Error : invalid request " + httpResponse.getStatusLine().getStatusCode()); } } catch (ClientProtocolException e) { showToaster(context, "Error : " + e.getLocalizedMessage()); } catch (IOException e) { showToaster(context, "Error : " + e.getLocalizedMessage()); } } }
From source file:io.gs2.identifier.Gs2IdentifierClient.java
/** * GSI?????<br>/*from w w w . j a v a2 s . c o m*/ * <br> * * @param request * @return ? */ public DescribeIdentifierResult describeIdentifier(DescribeIdentifierRequest request) { String url = Gs2Constant.ENDPOINT_HOST + "/user/" + (request.getUserName() == null || request.getUserName().equals("") ? "null" : request.getUserName()) + "/identifier"; List<NameValuePair> queryString = new ArrayList<>(); if (request.getPageToken() != null) queryString.add(new BasicNameValuePair("pageToken", String.valueOf(request.getPageToken()))); if (request.getLimit() != null) queryString.add(new BasicNameValuePair("limit", String.valueOf(request.getLimit()))); if (queryString.size() > 0) { url += "?" + URLEncodedUtils.format(queryString, "UTF-8"); } HttpGet get = createHttpGet(url, credential, ENDPOINT, DescribeIdentifierRequest.Constant.MODULE, DescribeIdentifierRequest.Constant.FUNCTION); if (request.getRequestId() != null) { get.setHeader("X-GS2-REQUEST-ID", request.getRequestId()); } return doRequest(get, DescribeIdentifierResult.class); }
From source file:edu.scripps.fl.pubchem.web.session.PCWebSession.java
/** * /*www. j a v a2 s . c om*/ * Returns a description xml file for an aid * * @param aid * @return * @throws Exception */ public InputStream getDescrXML(int aid) throws Exception { // if we don't provide the version, we get the latest one anyway. // http://pubchem.ncbi.nlm.nih.gov/assay/assay.cgi?aid=2551&version=1.1&q=expdesc_xmldisplay List<NameValuePair> params = addParameters(new ArrayList<NameValuePair>(), "aid", aid, "q", "expdesc_xmldisplay"); URI uri = URIUtils.createURI("http", SITE, 80, "/assay/assay.cgi", URLEncodedUtils.format(params, "UTF-8"), null); HttpResponse response = getHttpClient().execute(new HttpGet(uri)); return response.getEntity().getContent(); }
From source file:com.ibm.watson.WatsonTranslate.java
public String translate(String text) { String tweetTranslation = text; if (watsonLangPair != null && text != null && !text.equals("")) { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("txt", text)); qparams.add(new BasicNameValuePair("sid", watsonLangPair)); qparams.add(new BasicNameValuePair("rt", "text")); try {//www .j a v a 2 s .c o m Executor executor = Executor.newInstance(); URI serviceURI = new URI(baseURLTranslation).normalize(); String auth = usernameTranslation + ":" + passwordTranslation; byte[] response = executor .execute(Request.Post(serviceURI) .addHeader("Authorization", "Basic " + Base64.encodeBase64String(auth.getBytes())) .bodyString(URLEncodedUtils.format(qparams, "utf-8"), ContentType.APPLICATION_FORM_URLENCODED) .connectTimeout(15 * 1000)) .returnContent().asBytes(); tweetTranslation = new String(response, "UTF-8"); logger.debug("Translated {} to {}", text, tweetTranslation); } catch (Exception e) { logger.error("Watson error: {} on text: {}", e.getMessage(), text); } } return tweetTranslation; }
From source file:org.codegist.crest.HttpClientRestService.java
private static HttpUriRequest toHttpUriRequest(HttpRequest request) throws UnsupportedEncodingException { HttpUriRequest uriRequest;/* w ww . ja v a2s. co m*/ String queryString = ""; if (request.getQueryParams() != null) { List<NameValuePair> params = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : request.getQueryParams().entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } String qs = URLEncodedUtils.format(params, request.getEncoding()); queryString = Strings.isNotBlank(qs) ? ("?" + qs) : ""; } String uri = request.getUri().toString() + queryString; switch (request.getMeth()) { default: case GET: uriRequest = new HttpGet(uri); break; case POST: uriRequest = new HttpPost(uri); break; case PUT: uriRequest = new HttpPut(uri); break; case DELETE: uriRequest = new HttpDelete(uri); break; case HEAD: uriRequest = new HttpHead(uri); break; } if (uriRequest instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase enclosingRequestBase = ((HttpEntityEnclosingRequestBase) uriRequest); HttpEntity entity; if (Params.isForUpload(request.getBodyParams().values())) { MultipartEntity multipartEntity = new MultipartEntity(); for (Map.Entry<String, Object> param : request.getBodyParams().entrySet()) { ContentBody body; if (param.getValue() instanceof InputStream) { body = new InputStreamBody((InputStream) param.getValue(), param.getKey()); } else if (param.getValue() instanceof File) { body = new FileBody((File) param.getValue()); } else if (param.getValue() != null) { body = new StringBody(param.getValue().toString(), request.getEncodingAsCharset()); } else { body = new StringBody(null); } multipartEntity.addPart(param.getKey(), body); } entity = multipartEntity; } else { List<NameValuePair> params = new ArrayList<NameValuePair>(request.getBodyParams().size()); for (Map.Entry<String, Object> param : request.getBodyParams().entrySet()) { params.add(new BasicNameValuePair(param.getKey(), param.getValue() != null ? param.getValue().toString() : null)); } entity = new UrlEncodedFormEntity(params, request.getEncoding()); } enclosingRequestBase.setEntity(entity); } if (request.getHeaders() != null && !request.getHeaders().isEmpty()) { for (Map.Entry<String, String> header : request.getHeaders().entrySet()) { uriRequest.setHeader(header.getKey(), header.getValue()); } } if (request.getConnectionTimeout() != null && request.getConnectionTimeout() >= 0) { HttpConnectionParams.setConnectionTimeout(uriRequest.getParams(), request.getConnectionTimeout().intValue()); } if (request.getSocketTimeout() != null && request.getSocketTimeout() >= 0) { HttpConnectionParams.setSoTimeout(uriRequest.getParams(), request.getSocketTimeout().intValue()); } return uriRequest; }