List of usage examples for java.net URLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:info.magnolia.cms.exchange.simple.SimpleSyndicator.java
/** * add deactivation request header fields * * @param connection// w w w . jav a 2s . c o m */ protected void addDeactivationHeaders(URLConnection connection) { connection.setRequestProperty(AUTHORIZATION, this.basicCredentials); connection.addRequestProperty(REPOSITORY_NAME, this.repositoryName); connection.addRequestProperty(WORKSPACE_NAME, this.workspaceName); connection.addRequestProperty(PATH, this.path); connection.addRequestProperty(ACTION, DE_ACTIVATE); }
From source file:org.apache.jsp.fileUploader_jsp.java
public static String stringOfUrl(String addr, HttpServletRequest request, HttpServletResponse response) { if (localCookie) CookieHandler.setDefault(cm); try {// w w w.j a v a2s . c o m ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); URLConnection urlConnection = url.openConnection(); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Accept-Charset", "UTF-8"); } else if (DEBUG_MODE) System.out.println("Infinit.e Cookie Value is Null"); IOUtils.copy(urlConnection.getInputStream(), output); String newCookie = getConnectionInfiniteCookie(urlConnection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } String toReturn = output.toString(); output.close(); return toReturn; } catch (IOException e) { return null; } }
From source file:contestWebsite.Registration.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Entity contestInfo = Retrieve.contestInfo(); Map<String, String[]> params = new HashMap<String, String[]>(req.getParameterMap()); for (Entry<String, String[]> param : params.entrySet()) { if (!"studentData".equals(param.getKey())) { params.put(param.getKey(), new String[] { escapeHtml4(param.getValue()[0]) }); }//from w w w . j a v a2s.c om } String registrationType = params.get("registrationType")[0]; String account = "no"; if (params.containsKey("account")) { account = "yes"; } String email = params.containsKey("email") && params.get("email")[0].length() > 0 ? params.get("email")[0].toLowerCase().trim() : null; String schoolLevel = params.get("schoolLevel")[0]; String schoolName = params.get("schoolName")[0].trim(); String name = params.get("name")[0].trim(); String classification = params.containsKey("classification") ? params.get("classification")[0] : ""; String studentData = req.getParameter("studentData"); String password = null; String confPassword = null; UserCookie userCookie = UserCookie.getCookie(req); boolean loggedIn = userCookie != null && userCookie.authenticate(); if ((!loggedIn || !userCookie.isAdmin()) && email == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "E-Mail Address parameter ('email') must be specified"); return; } HttpSession sess = req.getSession(true); sess.setAttribute("registrationType", registrationType); sess.setAttribute("account", account); sess.setAttribute("account", account); sess.setAttribute("name", name); sess.setAttribute("classification", classification); sess.setAttribute("schoolName", schoolName); sess.setAttribute("schoolLevel", schoolLevel); sess.setAttribute("email", email); sess.setAttribute("studentData", studentData); boolean reCaptchaResponse = false; if (!(Boolean) sess.getAttribute("nocaptcha")) { URL reCaptchaURL = new URL("https://www.google.com/recaptcha/api/siteverify"); String charset = java.nio.charset.StandardCharsets.UTF_8.name(); String reCaptchaQuery = String.format("secret=%s&response=%s&remoteip=%s", URLEncoder.encode((String) contestInfo.getProperty("privateKey"), charset), URLEncoder.encode(req.getParameter("g-recaptcha-response"), charset), URLEncoder.encode(req.getRemoteAddr(), charset)); final URLConnection connection = new URL(reCaptchaURL + "?" + reCaptchaQuery).openConnection(); connection.setRequestProperty("Accept-Charset", charset); String response = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() { @Override public InputStream getInput() throws IOException { return connection.getInputStream(); } }, Charsets.UTF_8)); try { JSONObject JSONResponse = new JSONObject(response); reCaptchaResponse = JSONResponse.getBoolean("success"); } catch (JSONException e) { e.printStackTrace(); resp.sendRedirect("/contactUs?captchaError=1"); return; } } if (!(Boolean) sess.getAttribute("nocaptcha") && !reCaptchaResponse) { resp.sendRedirect("/registration?captchaError=1"); } else { if (account.equals("yes")) { password = params.get("password")[0]; confPassword = params.get("confPassword")[0]; } Query query = new Query("registration") .setFilter(new FilterPredicate("email", FilterOperator.EQUAL, email)).setKeysOnly(); List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)); if (users.size() != 0 && email != null || account.equals("yes") && !confPassword.equals(password)) { if (users.size() != 0) { resp.sendRedirect("/registration?userError=1"); } else if (!params.get("confPassword")[0].equals(params.get("password")[0])) { resp.sendRedirect("/registration?passwordError=1"); } else { resp.sendRedirect("/registration?updated=1"); } } else { Entity registration = new Entity("registration"); registration.setProperty("registrationType", registrationType); registration.setProperty("account", account); registration.setProperty("schoolName", schoolName); registration.setProperty("schoolLevel", schoolLevel); registration.setProperty("name", name); registration.setProperty("classification", classification); registration.setProperty("studentData", new Text(studentData)); registration.setProperty("email", email); registration.setProperty("paid", ""); registration.setProperty("timestamp", new Date()); JSONArray regData = null; try { regData = new JSONArray(studentData); } catch (JSONException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } long price = (Long) contestInfo.getProperty("price"); int cost = (int) (0 * price); for (int i = 0; i < regData.length(); i++) { try { JSONObject studentRegData = regData.getJSONObject(i); for (Subject subject : Subject.values()) { cost += price * (studentRegData.getBoolean(subject.toString()) ? 1 : 0); } } catch (JSONException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } } registration.setProperty("cost", cost); Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true)); try { datastore.put(registration); if (account.equals("yes") && password != null && password.length() > 0 && email != null) { Entity user = new Entity("user"); String hash = Password.getSaltedHash(password); user.setProperty("name", name); user.setProperty("school", schoolName); user.setProperty("schoolLevel", schoolLevel); user.setProperty("user-id", email); user.setProperty("salt", hash.split("\\$")[0]); user.setProperty("hash", hash.split("\\$")[1]); datastore.put(user); } txn.commit(); sess.setAttribute("props", registration.getProperties()); if (email != null) { Session session = Session.getDefaultInstance(new Properties(), null); String appEngineEmail = (String) contestInfo.getProperty("account"); String url = req.getRequestURL().toString(); url = url.substring(0, url.indexOf("/", 7)); try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(appEngineEmail, "Tournament Website Admin")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, name)); msg.setSubject("Thank you for your registration!"); VelocityEngine ve = new VelocityEngine(); ve.init(); VelocityContext context = new VelocityContext(); context.put("name", name); context.put("url", url); context.put("cost", cost); context.put("title", contestInfo.getProperty("title")); context.put("account", account.equals("yes")); StringWriter sw = new StringWriter(); Velocity.evaluate(context, sw, "registrationEmail", ((Text) contestInfo.getProperty("registrationEmail")).getValue()); msg.setContent(sw.toString(), "text/html"); Transport.send(msg); } catch (MessagingException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } } resp.sendRedirect("/registration?updated=1"); } catch (Exception e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); } finally { if (txn.isActive()) { txn.rollback(); } } } } }
From source file:com.google.android.dialer.provider.DialerProvider.java
private String executeHttpRequest(Uri uri) throws IOException { String charset = null;//from w w w .j a v a 2s .c o m if (Log.isLoggable("DialerProvider", Log.VERBOSE)) { Log.v("DialerProvider", "executeHttpRequest(" + uri + ")"); } try { URLConnection conn = new URL(uri.toString()).openConnection(); conn.setRequestProperty("User-Agent", mUserAgent); InputStream inputStream = conn.getInputStream(); charset = getCharsetFromContentType(conn.getContentType()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buf = new byte[1000]; while (true) { int len = inputStream.read(buf); if (len <= 0) { break; } outputStream.write(buf, 0, len); } inputStream.close(); outputStream.flush(); return new String(outputStream.toByteArray(), charset); } catch (UnsupportedEncodingException e) { Log.w("DialerProvider", "Invalid charset: " + charset, e); } catch (IOException e) { // TODO: Didn't find anything that goes here in byte-code } // TODO: Is this appropriate? return null; }
From source file:dreamboxdataservice.DreamboxDataService.java
private void getEPGData(TvDataUpdateManager updateManager, Channel ch) { try {/*from w ww . ja v a2 s .c o m*/ URL url = new URL("http://" + mProperties.getProperty("ip", "") + "/web/epgservice?sRef=" + StringUtils.replace(StringUtils.replace(ch.getId().substring(5), "_", ":"), " ", "%20")); URLConnection connection = url.openConnection(); String userpassword = mProperties.getProperty("username", "") + ":" + IOUtilities .xorEncode(mProperties.getProperty("password", ""), DreamboxSettingsPanel.PASSWORDSEED); String encoded = new String(Base64.encodeBase64(userpassword.getBytes())); connection.setRequestProperty("Authorization", "Basic " + encoded); connection.setConnectTimeout(60); InputStream stream = connection.getInputStream(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); DreamboxChannelHandler handler = new DreamboxChannelHandler(updateManager, ch); saxParser.parse(stream, handler); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:io.s4.latin.adapter.TwitterFeedListener.java
public void connectAndRead() throws Exception { URL url = new URL(urlString); URLConnection connection = url.openConnection(); connection.setConnectTimeout(10000); connection.setReadTimeout(10000);/*ww w.ja va2 s . c o m*/ String userPassword = userid + ":" + password; System.out.println("connect to " + connection.getURL().toString() + " ..."); String encoded = EncodingUtil.getAsciiString(Base64.encodeBase64(EncodingUtil.getAsciiBytes(userPassword))); connection.setRequestProperty("Authorization", "Basic " + encoded); connection.setRequestProperty("Accept-Charset", "utf-8,ISO-8859-1"); connection.connect(); System.out.println("Connect OK!"); System.out.println("Reading TwitterFeed ...."); Long startTime = new Date().getTime(); InputStream is = connection.getInputStream(); Charset utf8 = Charset.forName("UTF-8"); InputStreamReader isr = new InputStreamReader(is, utf8); BufferedReader br = new BufferedReader(isr); String inputLine = null; while ((inputLine = br.readLine()) != null) { if (inputLine.trim().length() == 0) { blankCount++; continue; } messageCount++; messageQueue.add(inputLine); if (messageCount % 500 == 0) { Long currentTime = new Date().getTime(); System.out.println("Lines processed: " + messageCount + "\t ( " + blankCount + " empty lines ) in " + (currentTime - startTime) / 1000 + " seconds. Reading " + messageCount / ((currentTime - startTime) / 1000) + " rows/second"); } } }
From source file:dreamboxdataservice.DreamboxDataService.java
/** * @param service Service-ID/*from w ww . java2 s . c om*/ * @return Data of specific service */ public TreeMap<String, String> getServiceData(String service) { try { URL url = new URL("http://" + mProperties.getProperty("ip", "") + "/web/getservices?sRef=" + service); URLConnection connection = url.openConnection(); String userpassword = mProperties.getProperty("username", "") + ":" + IOUtilities .xorEncode(mProperties.getProperty("password", ""), DreamboxSettingsPanel.PASSWORDSEED); String encoded = new String(Base64.encodeBase64(userpassword.getBytes())); connection.setRequestProperty("Authorization", "Basic " + encoded); connection.setConnectTimeout(10); InputStream stream = connection.getInputStream(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); DreamboxHandler handler = new DreamboxHandler(); saxParser.parse(stream, handler); return handler.getData(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:org.xbmc.httpapi.Connection.java
/** * Create a new URLConnection with the request headers set, including authentication. * * @param url The request url// ww w .j a v a2 s. c o m * @return URLConnection * @throws IOException */ private URLConnection getUrlConnection(URL url) throws IOException { final URLConnection uc = url.openConnection(); uc.setConnectTimeout(SOCKET_CONNECTION_TIMEOUT); uc.setReadTimeout(mSocketReadTimeout); uc.setRequestProperty("Connection", "close"); if (authEncoded != null) { uc.setRequestProperty("Authorization", "Basic " + authEncoded); } return uc; }
From source file:dreamboxdataservice.DreamboxDataService.java
/** * @param service Service-ID//ww w. ja v a 2s . c om * @return Data of specific service */ public TreeMap<String, String> getServiceDataBonquets(String service) { try { URL url = new URL("http://" + mProperties.getProperty("ip", "") + "/web/getservices?bRef=" + service); URLConnection connection = url.openConnection(); String userpassword = mProperties.getProperty("username", "") + ":" + IOUtilities .xorEncode(mProperties.getProperty("password", ""), DreamboxSettingsPanel.PASSWORDSEED); String encoded = new String(Base64.encodeBase64(userpassword.getBytes())); connection.setRequestProperty("Authorization", "Basic " + encoded); connection.setConnectTimeout(10); InputStream stream = connection.getInputStream(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); DreamboxHandler handler = new DreamboxHandler(); saxParser.parse(stream, handler); return handler.getData(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:de.uni_koblenz.aggrimm.icp.interfaceAgents.bing.BingRetriever.java
/** * * <p>Returns the results queried for. * * @param encodedSearchTerm the term to search for. * @param source where to search. * @param market for localised results. * @param top number of results. * @param skip offset for the starting point of results returned. * * For more details on the parameters, please have a look at: * * @see #createBasicQueryString(java.lang.String, java.lang.String, * java.lang.String, int, int)//w ww . j ava 2 s . com * * @return {@code IWebResult} if {@code market} is "web" * and {@code IImageResult} if market is "image" in an * {@code BingResultsContainer}. * @throws MalformedURLException if {@code createBasicQueryString}'s result * cannot be transformed into a URL. * @throws URISyntaxException if {@code createBasicQueryString}'s result * cannot be transformed into a URL. * @throws IOException if an I/O exception occurs while trying to * open the URL connection or while trying to * read the results. * @throws ParseException if the resultString cannot be properly parsed * from. */ @Override public BingResultsContainer<IResult> doSearch(String encodedSearchTerm, String source, String market, int top, int skip) throws MalformedURLException, URISyntaxException, IOException, ParseException { String queryString = createBasicQueryString(encodedSearchTerm, source, market, top, skip); URL query = new URL(queryString); URLConnection queryURLConnection = query.openConnection(); if (API_KEY == null) { throw new IllegalStateException( "The API key for bing could not be read from the application.xml. Make sure it was set."); } byte[] apiRequestBytes = ("ignored:" + API_KEY).getBytes(Charset.forName("UTF-8")); String encodedApiKey = DatatypeConverter.printBase64Binary(apiRequestBytes); queryURLConnection.setRequestProperty("Authorization", "Basic " + encodedApiKey); try (BufferedReader in = new BufferedReader( new InputStreamReader(queryURLConnection.getInputStream(), Charset.forName("UTF-8")))) { String resultString = in.readLine(); // it's a one-liner, so this is enough IResultsContainer<IResult> resultList = brc.parseJSONString(resultString, source, skip); assert (resultList instanceof BingResultsContainer<?>); return (BingResultsContainer<IResult>) resultList; } catch (IOException e) { LOGGER.log(Level.INFO, "Bing input stream could not be fetched: {0}", e); throw new IOException("Couldn't fetch Bing input stream."); } }