List of usage examples for java.net URLEncoder encode
public static String encode(String s, Charset charset)
From source file:com.google.api.translate.Translate.java
/** * Translates text from a given Language to another given Language using Google Translate. * //from w w w. j av a 2 s. co m * @param text The String to translate. * @param from The language code to translate from. * @param to The language code to translate to. * @return The translated String. * @throws Exception on error. */ public static String execute(final String text, final Language from, final Language to) throws Exception { validateReferrer(); final URL url = new URL(URL); final String parameters = PARAMETERS.replaceAll("#FROM#", from.toString()).replaceAll("#TO#", to.toString()) + URLEncoder.encode(text, ENCODING); final JSONObject json = retrieveJSON(url, parameters); return getJSONResponse(json); }
From source file:connector.ISConnector.java
public static JSONObject validateToken(String accessToken) { JSONObject response = null;//ww w .ja v a 2s .com try { String utf8 = java.nio.charset.StandardCharsets.UTF_8.name(); String query = String.format("token=%s", URLEncoder.encode(accessToken, utf8)); response = processRequest("/auth", query.getBytes()); } catch (Exception e) { e.printStackTrace(); } return response; }
From source file:com.rastating.droidbeard.net.SearchTvDBTask.java
@Override protected TvDBResult[] doInBackground(String... strings) { String name = null;//from w w w . ja v a 2 s . c om try { name = URLEncoder.encode(strings[0], "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); name = strings[0]; } try { String json = getJson("sb.searchtvdb", "name", name); List<TvDBResult> list = new ArrayList<TvDBResult>(); if (json != null && !json.equals("")) { JSONArray results = new JSONObject(json).getJSONObject("data").getJSONArray("results"); for (int i = 0; i < results.length(); i++) { JSONObject result = results.getJSONObject(i); TvDBResult tvDBResult = new TvDBResult(); tvDBResult.setFirstAired(result.getString("first_aired")); tvDBResult.setName(result.getString("name")); tvDBResult.setId(result.getLong("tvdbid")); list.add(tvDBResult); } return list.toArray(new TvDBResult[list.size()]); } else { return null; } } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:de.bayern.gdi.utils.StringUtils.java
/** * URL-encodes a given string in a given encoding. * @param s The string to encode.// w ww .java 2 s.co m * @param enc The encoding to use. * @return The encodes string. */ public static String urlEncode(String s, String enc) { try { return URLEncoder.encode(s, enc); } catch (UnsupportedEncodingException e) { log.log(Level.SEVERE, "encoding problem", e); } return s; }
From source file:models.service.UserInfoCookieService.java
/** * ?COOKIE/*ww w.ja v a2 s .c om*/ * * @param isForce ?COOKIE?? */ public static void createOrUpdateCookie(boolean isForce) { Context ct = Context.current(); if (MobileUtil.isMobileUrlPrefix(ct.request().path())) { return; } User user = User.getFromSession(ct.session()); if (null != user) { Long userId = user.getId(); String username = user.getName(); String token = UserAuthService.getTokenInSession(ct.session()); Long userIdInCookie = cookieValueToLong(Constants.COOKIE_USERINFO_ID); String usernameInCookie = cookieValueToDecodedString(Constants.COOKIE_USERINFO_NAME); String tokenInCookie = cookieValueToDecodedString(Constants.COOKIE_USERINFO_TOKEN); if (isForce || !Objects.equals(userIdInCookie, userId)) { ct.response().setCookie(Constants.COOKIE_USERINFO_ID, String.valueOf(userId)); } if (isForce || !Objects.equals(usernameInCookie, username)) { try { ct.response().setCookie(Constants.COOKIE_USERINFO_NAME, URLEncoder.encode(username, "UTF-8")); } catch (UnsupportedEncodingException e) { LOGGER.error("URL?", e); } } if (isForce || !Objects.equals(tokenInCookie, token)) { try { ct.response().setCookie(Constants.COOKIE_USERINFO_TOKEN, URLEncoder.encode(token, "UTF-8")); } catch (UnsupportedEncodingException e) { LOGGER.error("URL?", e); } } } }
From source file:com.lll.util.EncodeUtils.java
/** * URL ?.//from w w w .j a v a2s. c o m */ public static String urlEncode(String input, String encoding) { try { return URLEncoder.encode(input, encoding); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("Unsupported Encoding Exception", e); } }
From source file:com.aws.image.test.TestFlickrAPI.java
public static String callFlickrAPIForEachKeyword(String query, String synsetCode, String safeSearch, int urlsPerKeyword) throws IOException, JSONException { String apiKey = "ad4f88ecfd53b17f93178e19703fe00d"; String apiSecret = "96cab0e9f89468d6"; int total = 500; int perPage = 500; System.out.println("\n\t\t KEYWORD::" + query); System.out.println("\t No. of urls required::" + urlsPerKeyword); int totalPages; if (urlsPerKeyword % perPage != 0) totalPages = (urlsPerKeyword / perPage) + 1; else/*from w w w.j a v a 2s. co m*/ totalPages = urlsPerKeyword / perPage; System.out.println("\n\n\t total pages ::" + totalPages); int currentCount = 0; int eachPage; List<Document> documentsInBatch = new ArrayList<>(); for (int i = 1; i <= totalPages && currentCount <= total; i++, currentCount = currentCount + perPage) { documentsInBatch = new ArrayList<>(); eachPage = urlsPerKeyword < perPage ? urlsPerKeyword : perPage; StringBuffer sb = new StringBuffer(512); sb.append("https://api.flickr.com/services/rest/?method=flickr.photos.search&text=") .append(URLEncoder.encode(query, "UTF-8")).append("&safe_search=").append(safeSearch) .append("&extras=url_c,url_m,url_n,license,owner_name&per_page=").append(eachPage) .append("&page=").append(i).append("&format=json&api_key=").append(apiKey) .append("&api_secret=").append(apiSecret).append("&license=4,5,6,7,8"); String url = sb.toString(); System.out.println("URL FORMED --> " + url); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); CloseableHttpResponse httpResponse = httpClient.execute(httpGet); //System.out.println("GET Response Status:: " + httpResponse.getStatusLine().getStatusCode()); BufferedReader reader = new BufferedReader( new InputStreamReader(httpResponse.getEntity().getContent())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = reader.readLine()) != null) { response.append(inputLine); } reader.close(); String responseString = response.toString(); responseString = responseString.replace("jsonFlickrApi(", ""); int length = responseString.length(); responseString = responseString.substring(0, length - 1); // print result httpClient.close(); JSONObject json = null; try { json = new JSONObject(responseString); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } //System.out.println("Converted JSON String " + json); JSONObject photosObj = json.has("photos") ? json.getJSONObject("photos") : null; total = photosObj.has("total") ? (Integer.parseInt(photosObj.getString("total"))) : 0; perPage = photosObj.has("perpage") ? (Integer.parseInt(photosObj.getString("perpage"))) : 0; //System.out.println(" perPage --> " + perPage + " total --> " + total); JSONArray photoArr = photosObj.getJSONArray("photo"); //System.out.println("Length of Array --> " + photoArr.length()); String scrapedImageURL = ""; for (int itr = 0; itr < photoArr.length(); itr++) { JSONObject tempObject = photoArr.getJSONObject(itr); scrapedImageURL = tempObject.has("url_c") ? tempObject.getString("url_c") : tempObject.has("url_m") ? tempObject.getString("url_m") : tempObject.has("url_n") ? tempObject.getString("url_n") : null; if (scrapedImageURL == null) { continue; } String contributor = tempObject.getString("ownername"); String license = tempObject.getString("license"); //System.out.println("Scraped Image URL, need to insert this to Mongo DB --> " + scrapedImageURL); //documentsInBatch.add(getDocumentPerCall(scrapedImageURL, contributor, license, safeSearch)); counter++; } //insertData(documentsInBatch); } System.out.println("F L I C K R C O U N T E R -> " + counter); //insertData(documentsInBatch); //countDownLatchForImageURLs.countDown(); return null; }
From source file:net.sf.arbocdi.ser.searcher.GoogleSearcher.java
public String makeURIString(String searchText) throws URISyntaxException, UnsupportedEncodingException { searchText = URLEncoder.encode(searchText, "UTF-8"); return String.format("https://www.google.com/search?ie=utf-8&oe=utf-8&q=%s", searchText); }
From source file:com.nkapps.billing.services.SearchServiceImpl.java
@Override public String execSearchBy(HttpServletRequest request, HttpServletResponse response) throws Exception { Cookie sbtCookie = null;//from w w w . jav a 2s .co m String searchBy = request.getParameter("searchBy"); if (searchBy == null) { Cookie[] requestCookies = request.getCookies(); for (Cookie c : requestCookies) { if (c.getName().equals("searchBy")) { sbtCookie = c; } } if (sbtCookie != null) { searchBy = URLDecoder.decode(sbtCookie.getValue(), "UTF-8"); } else { searchBy = ""; } } else { sbtCookie = new Cookie("searchBy", URLEncoder.encode(searchBy, "UTF-8")); sbtCookie.setPath("/"); response.addCookie(sbtCookie); } return searchBy; }
From source file:com.fluidops.iwb.cms.util.OpenUp.java
public static List<Statement> extract(String text, URI uri) throws IOException { List<Statement> res = new ArrayList<Statement>(); String textEncoded = URLEncoder.encode(text, "UTF-8"); String send = "format=rdfxml&text=" + textEncoded; // service limit is 10000 chars if (mode() == Mode.demo) send = stripToDemoLimit(send);/*from www . j a v a2 s .c o m*/ // GET only works for smaller texts // URL url = new URL("http://openup.tso.co.uk/des/enriched-text?text=" + textEncoded + "&format=rdfxml"); URL url = new URL(getConfig().getOpenUpUrl()); URLConnection conn = url.openConnection(); conn.setDoOutput(true); IOUtils.write(send, conn.getOutputStream()); Repository repository = new SailRepository(new MemoryStore()); try { repository.initialize(); RepositoryConnection con = repository.getConnection(); con.add(conn.getInputStream(), uri.stringValue(), RDFFormat.RDFXML); RepositoryResult<Statement> iter = con.getStatements(null, null, null, false); while (iter.hasNext()) { Statement s = iter.next(); res.add(s); } } catch (Exception e) { throw new RuntimeException(e); } return res; }