List of usage examples for java.net URLEncoder encode
public static String encode(String s, Charset charset)
From source file:com.frostwire.android.gui.views.SuggestionsAdapter.java
@Override public Cursor runQueryOnBackgroundThread(CharSequence constraint) { try {/* w ww . j a v a 2s . c o m*/ String url = String.format(SUGGESTIONS_URL, URLEncoder.encode(constraint.toString(), "UTF-8")); String json = client.get(url, HTTP_QUERY_TIMEOUT); if (!discardLastResult) { return new SuggestionsCursor(new JSONArray(json).getJSONArray(1)); } } catch (Throwable e) { // ignore } finally { discardLastResult = false; } return null; }
From source file:com.appzone.sim.services.handlers.SendMoServiceHandler.java
@Override protected String doProcess(HttpServletRequest request) { String address = request.getParameter(KEY_ADDRESS); String message = request.getParameter(KEY_MESSAGE); String correlator = "" + ((int) (Math.random() * 10000000000000L)); try {/* w w w . j a va 2 s . co m*/ String queryString = String.format("version=1.0&address=%s&message=%s&correlator=%s", address, URLEncoder.encode(message, "UTF-8"), URLEncoder.encode(correlator, "UTF-8")); logger.info("sending MO request as: {}", queryString); String response = http.excutePost(application.getUrl(), queryString); logger.debug("getting response as: {}", response); JSONObject json = new JSONObject(); json.put(ServiceHandler.JSON_KEY_RESULT, response); return json.toJSONString(); } catch (Exception e) { logger.error("Error while sending http request", e); JSONObject json = new JSONObject(); json.put(ServiceHandler.JSON_KEY_ERROR, e.getMessage()); return json.toJSONString(); } }
From source file:com.alta189.cyborg.commandkit.util.HttpUtil.java
public static String encode(String raw) { String result = null;//from w w w. java 2 s . co m try { result = URLEncoder.encode(raw, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; }
From source file:com.smedic.tubtub.JsonAsyncTask.java
@Override protected ArrayList<String> doInBackground(String... params) { //encode param to avoid spaces in URL String encodedParam = ""; try {/*w ww . j a va 2 s .c o m*/ encodedParam = URLEncoder.encode(params[0], "UTF-8").replace("+", "%20"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } ArrayList<String> items = new ArrayList<>(); try { URL url = new URL( "http://suggestqueries.google.com/complete/search?client=youtube&ds=yt&q=" + encodedParam); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // gets the server json data BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(urlConnection.getInputStream())); String next; while ((next = bufferedReader.readLine()) != null) { if (checkJson(next) == JSON_ERROR) { //if not valid, remove invalid parts (this is simple hack for URL above) next = next.substring(19, next.length() - 1); } JSONArray ja = new JSONArray(next); for (int i = 0; i < ja.length(); i++) { if (ja.get(i) instanceof JSONArray) { JSONArray ja2 = ja.getJSONArray(i); for (int j = 0; j < ja2.length(); j++) { if (ja2.get(j) instanceof JSONArray) { String suggestion = ((JSONArray) ja2.get(j)).getString(0); //Log.d(TAG, "Suggestion: " + suggestion); items.add(suggestion); } } } else if (ja.get(i) instanceof JSONObject) { //Log.d(TAG, "json object"); } else { //Log.d(TAG, "unknown object"); } } } } catch (IOException | JSONException e) { e.printStackTrace(); } return items; }
From source file:org.jasig.portlet.cms.controller.DownloadPostAttachmentController.java
@RequestMapping protected void handleRequest(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final HttpSession session = request.getSession(); final Attachment attachment = (Attachment) session.getAttribute("attachment"); logDebug("Attempting to download attachment: " + attachment); response.setContentType("application/x-download"); logDebug("Set content type to: " + response.getContentType()); final String encoding = response.getCharacterEncoding(); logDebug("Encoded file name based on: " + encoding); final String fileName = URLEncoder.encode(attachment.getFileName(), encoding); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); logDebug("Downloading file: " + fileName); final OutputStream out = response.getOutputStream(); out.write(attachment.getContents()); out.flush();//from w ww .ja va 2 s. c om logDebug("Clearing session attribute"); session.setAttribute("attachment", null); }
From source file:com.neelo.glue.st.StringRenderer.java
public String toString(Object o, String format) { try {/* w w w . j a v a 2s . c o m*/ String[] formats = format.split("[,]"); String formatted = o.toString(); for (String f : formats) { f = f.trim(); if (f.equals("uppercase")) formatted = formatted.toUpperCase(); else if (f.equals("lowercase")) formatted = formatted.toLowerCase(); else if (f.equals("capitalize")) formatted = StringUtils.capitalize(formatted); else if (f.startsWith("abbreviate")) { String[] parts = f.split("[:]"); if (parts.length == 2) { formatted = StringUtils.abbreviate(formatted, Integer.parseInt(parts[1].trim())); } } else if (f.equals("encode")) formatted = URLEncoder.encode(o.toString(), "UTF-8"); else if (f.equals("csv")) { formatted = formatted.replace("\"", "\"\""); formatted = "\"" + formatted + "\""; } } return formatted; } catch (Exception e) { return toString(o); } }
From source file:com.cloud.test.longrun.VirtualMachine.java
public void deployVM(long zoneId, long serviceOfferingId, long templateId, String server, String apiKey, String secretKey) throws IOException { String encodedZoneId = URLEncoder.encode("" + zoneId, "UTF-8"); String encodedServiceOfferingId = URLEncoder.encode("" + serviceOfferingId, "UTF-8"); String encodedTemplateId = URLEncoder.encode("" + templateId, "UTF-8"); String encodedApiKey = URLEncoder.encode(apiKey, "UTF-8"); String requestToSign = "apiKey=" + encodedApiKey + "&command=deployVirtualMachine&serviceOfferingId=" + encodedServiceOfferingId + "&templateId=" + encodedTemplateId + "&zoneId=" + encodedZoneId; requestToSign = requestToSign.toLowerCase(); String signature = TestClientWithAPI.signRequest(requestToSign, secretKey); String encodedSignature = URLEncoder.encode(signature, "UTF-8"); String url = server + "?command=deployVirtualMachine" + "&zoneId=" + encodedZoneId + "&serviceOfferingId=" + encodedServiceOfferingId + "&templateId=" + encodedTemplateId + "&apiKey=" + encodedApiKey + "&signature=" + encodedSignature; s_logger.info("Sending this request to deploy a VM: " + url); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int responseCode = client.executeMethod(method); s_logger.info("deploy linux vm response code: " + responseCode); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> values = TestClientWithAPI.getSingleValueFromXML(is, new String[] { "id", "ipaddress" }); long linuxVMId = Long.parseLong(values.get("id")); s_logger.info("got linux virtual machine id: " + linuxVMId); this.setPrivateIp(values.get("ipaddress")); } else if (responseCode == 500) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> errorInfo = TestClientWithAPI.getSingleValueFromXML(is, new String[] { "errorcode", "description" }); s_logger.error("deploy linux vm test failed with errorCode: " + errorInfo.get("errorCode") + " and description: " + errorInfo.get("description")); } else {/*from w w w . j av a 2s. c o m*/ s_logger.error("internal error processing request: " + method.getStatusText()); } }
From source file:org.wso2.carbon.tryit.WADLTryItRequestProcessor.java
@Override public void process(CarbonHttpRequest request, CarbonHttpResponse response, ConfigurationContext configurationContext) throws Exception { OutputStream outputStream = response.getOutputStream(); response.addHeader(HTTP.CONTENT_TYPE, "text/html; charset=utf-8"); response.addHeader("Access-Control-Allow-Origin", "*"); Result result = new StreamResult(outputStream); String url = request.getParameter("resourceurl"); url = URLEncoder.encode(url.toString(), "UTF-8"); String contextRoot = CarbonUtils.getServerConfiguration().getFirstProperty("WebContextRoot"); outputStream.write(("<meta content=\"text/html;charset=utf-8\" http-equiv=\"Content-Type\">\n" + "<meta content=\"utf-8\" http-equiv=\"encoding\">").getBytes()); outputStream.write(//w w w . j a va 2 s . com ("<script type='text/javascript' src='?wadl2form&contentType=text/javascript&resource=js/jquery-1.8.0.min.js'></script>") .getBytes()); outputStream.write( ("<script type='text/javascript' src='?wadl2form&contentType=text/javascript&resource=js/jquery.slideto.min.js'></script>") .getBytes()); outputStream.write( ("<script type='text/javascript' src='?wadl2form&contentType=text/javascript&resource=js/jquery.wiggle.min.js'></script>") .getBytes()); outputStream.write( ("<script type='text/javascript' src='?wadl2form&contentType=text/javascript&resource=js/jquery.ba-bbq.min.js'></script>") .getBytes()); outputStream.write( ("<script type='text/javascript' src='?wadl2form&contentType=text/javascript&resource=js/handlebars-1.0.rc.1.js'></script>") .getBytes()); outputStream.write( ("<script type='text/javascript' src='?wadl2form&contentType=text/javascript&resource=js/underscore-min.js'></script>") .getBytes()); outputStream.write( ("<script type='text/javascript' src='?wadl2form&contentType=text/javascript&resource=js/backbone-min.js'></script>") .getBytes()); outputStream.write( ("<script type='text/javascript' src='?wadl2form&contentType=text/javascript&resource=js/swagger.js'></script>") .getBytes()); outputStream.write( ("<script type='text/javascript' src='?wadl2form&contentType=text/javascript&resource=js/swagger-ui.js'></script>") .getBytes()); outputStream.write( ("<script type='text/javascript' src='?wadl2form&contentType=text/javascript&resource=js/jquery.base64.js'></script>") .getBytes()); outputStream.write( ("<link rel='stylesheet' type='text/css' href='?wadl2form&contentType=text/css&resource=css/screen.css'/>") .getBytes()); outputStream.write(("\n" + "<style type='text/css'>\n" + " .swagger-ui-wrap {\n" + " max-width: 960px;\n" + " margin-left: auto;\n" + " margin-right: auto;\n" + " }\n" + "\n" + " .icon-btn {\n" + " cursor: pointer;\n" + " }\n" + "\n" + " #message-bar {\n" + " min-height: 30px;\n" + " text-align: center;\n" + " padding-top: 10px;\n" + " }\n" + "\n" + " .message-success {\n" + " color: #89BF04;\n" + " }\n" + "\n" + " .message-fail {\n" + " color: #cc0000;\n" + " }\n" + "</style>\n" + "\n" + "<script type='text/javascript'>\n" + " $(function () {\n" + " window.swaggerUi = new SwaggerUi({\n" + " discoveryUrl: '?wadl2form&contentType=application/json&resource=swaggerurl&wadldocurl=" + url + "',\n" + " dom_id: 'swagger-ui-container',\n" + " apiKeyName: 'authorization',\n" + " supportHeaderParams: true,\n" + " supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'options'],\n" + " onComplete: function (swaggerApi, swaggerUi) {\n" + " if (console) {\n" + " console.log('Loaded SwaggerUI');\n" + " console.log(swaggerApi);\n" + " console.log(swaggerUi);\n" + " }\n" + " $('ul.endpoints').show();\n" + " },\n" + " onFailure: function (data) {\n" + " if (console) {\n" + " console.log('Unable to Load SwaggerUI');\n" + " console.log(data);\n" + " }\n" + " },\n" + " docExpansion: 'none'\n" + " });\n" + " window.swaggerUi.load();\n" + " });\n" + "</script>\n" + "<div id='swagger-ui-container'>Please wait while loading try it page....</div>\n" + "<style>\n" + " html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {\n" + " font-family: Arial, Helvetica, Verdana, monospace, san-serif;\n" + " font-size: 12px;\n" + " line-height: 20px;\n" + " }\n" + "\n" + " div#overview ul {\n" + " list-style: disc;\n" + " margin: 5px 5px 5px 18px;\n" + " }\n" + "\n" + " div#overview li {\n" + " padding-bottom: 5px;\n" + " }\n" + "\n" + " h2 {\n" + " font-size: 24px;\n" + " line-height: normal;\n" + " font-weight: bold;\n" + " }\n" + "\n" + " .search-back body {\n" + " line-hieight: 18px;\n" + " }\n" + "\n" + " body ul#resources li.resource div.heading h2 a {\n" + " color: #111111;\n" + " }\n" + "\n" + " .search-back {\n" + " padding: 0 0 0 20px;\n" + " }\n" + "\n" + " ul.endpoints {\n" + " padding: 10px;\n" + " border: solid 1px #efefef;\n" + " }\n" + "\n" + " body ul#resources li.resource div.heading {\n" + " background: #EFEFEF;\n" + " padding: 0 10px;\n" + " }\n" + "\n" + " body ul#resources li.resource div.heading ul.options {\n" + " margin: 23px 10px 0 0;\n" + " }\n" + "\n" + " h6 {\n" + " color: inherit;\n" + " font-family: inherit;\n" + " font-weight: bold;\n" + " line-height: 20px;\n" + " margin: 0 0 10px 0;\n" + " text-rendering: optimizelegibility;\n" + " }\n" + "\n" + " h5 {\n" + " color: inherit;\n" + " font-family: inherit;\n" + " font-size: 18px;\n" + " font-weight: bold;\n" + " line-height: 20px;\n" + " margin: 10px 0;\n" + " text-rendering: optimizelegibility;\n" + " }\n" + "</style>\n").getBytes()); outputStream.write( ("<input type='hidden' name='contextRoot_name' id='contextRoot' value='" + contextRoot + "'>") .getBytes()); outputStream.flush(); }
From source file:es.upm.dit.gsi.noticiastvi.gtv.account.CreateThread.java
@Override public void run() { DefaultHttpClient client = new DefaultHttpClient(); StringBuilder query = new StringBuilder(); try {// ww w . j av a 2 s .c o m query.append(Constant.SERVER_URL + "?action=" + ACTION + "&name="); query.append(URLEncoder.encode(username.trim(), "UTF-8")); HttpGet get = new HttpGet(query.toString()); HttpResponse getResponse = client.execute(get); final int statusCode = getResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(getClass().getSimpleName(), "Error " + statusCode); handler.sendEmptyMessage(RESULT_ERROR); return; } InputStream source = getResponse.getEntity().getContent(); if (source != null) { Gson gson = new Gson(); Reader reader = new InputStreamReader(source); Account account = gson.fromJson(reader, Account.class); if (account.getNombre() != null && account.getNombre() != "") { handler.sendMessage(Message.obtain(handler, RESULT_OK, account)); } else { handler.sendEmptyMessage(RESULT_ERROR); } } else { handler.sendEmptyMessage(RESULT_ERROR); } } catch (Exception e) { handler.sendEmptyMessage(RESULT_ERROR); Log.e("ERROR", e.getMessage()); } }
From source file:com.controller.CuotasController.java
@RequestMapping("cuotas.htm") public ModelAndView getCuotas(HttpServletRequest request) { sesion = request.getSession();/*from ww w. jav a 2 s.c o m*/ ModelAndView mav = new ModelAndView(); String mensaje = null; Detalles detalle = (Detalles) sesion.getAttribute("cuenta"); String country = detalle.getCiudad(); String amount = "5"; String myURL = "http://192.168.5.39/app_dev.php/public/get/rates"; // System.out.println("Requested URL:" + myURL); StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null; try { URL url = new URL(myURL); urlConn = url.openConnection(); if (urlConn != null) { urlConn.setReadTimeout(60 * 1000); urlConn.setDoOutput(true); String data = URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8"); data += "&" + URLEncoder.encode("amount", "UTF-8") + "=" + URLEncoder.encode(amount, "UTF-8"); System.out.println("los Datos a enviar por POST son " + data); try ( //obtenemos el flujo de escritura OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) { //escribimos wr.write(data); wr.flush(); //cerramos la conexin } } if (urlConn != null && urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) { int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Exception while calling URL:" + myURL, e); } String resultado = sb.toString(); if (sesion.getAttribute("usuario") == null) { mav.setViewName("login/login"); } else { sesionUser = sesion.getAttribute("usuario").toString(); //Detalles detalle = (Detalles) sesion.getAttribute("cuenta"); mav.addObject("country", detalle.getCiudad()); mav.addObject("resultado", resultado); if (sesion.getAttribute("tipoUsuario").toString().compareTo("Administrador") == 0) { mav.setViewName("viewsAdmin/cuotasAdmin"); System.out.println("el usuario es administrador"); } else { mav.setViewName("panel/cuotas"); } } return mav; }