List of usage examples for java.net URLConnection addRequestProperty
public void addRequestProperty(String key, String value)
From source file:com.googlecode.mashups.services.google.impl.GoogleSearchServiceImpl.java
public List<GoogleSearchResultItem> getWebSearchResultList(List<ServiceParameter> parameters) throws Exception { parameters = prepareQueryParameters(parameters); URL feedUrl = new URL( GOOGLE_SEARCH_SERVICE_URL + "?" + ServiceParametersUtility.toParametersString(parameters)); List<GoogleSearchResultItem> searchResults = new ArrayList<GoogleSearchResultItem>(); URLConnection connection = feedUrl.openConnection(); connection.addRequestProperty(REFERER, REFERER_VALUE); String line;//from ww w .j a va2 s. c o m StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { builder.append(line); } JSONObject json = new JSONObject(builder.toString()); JSONObject root = (JSONObject) json.get(RESPONSE_DATA_ROOT); JSONArray results = root.getJSONArray(RESPONSE_DATA_RESULTS); for (int i = 0; i < results.length(); ++i) { JSONObject searchItem = (JSONObject) results.get(i); // Get attributes. String title = (String) searchItem.get(TITLE); String titleNotFormatting = (String) searchItem.get(TITLE_NO_FORMATTING); String content = (String) searchItem.get(CONTENT); String cacheUrl = (String) searchItem.get(CACHE_URL); String unescapedUrl = (String) searchItem.get(UNESCAPED_URL); String visibleUrl = (String) searchItem.get(VISIBLE_URL); String url = (String) searchItem.get(URL); String GsearchResultClass = (String) searchItem.get(GSEARCH_RESULT_CLASS); // Fill the GoogleSearchResultItem. GoogleSearchResultItem googleSearchResultItem = new GoogleSearchResultItem(); googleSearchResultItem.setTitle(title); googleSearchResultItem.setTitleNotFormatting(titleNotFormatting); googleSearchResultItem.setContent(content); googleSearchResultItem.setCacheUrl(cacheUrl); googleSearchResultItem.setUnescapedUrl(unescapedUrl); googleSearchResultItem.setVisibleUrl(visibleUrl); googleSearchResultItem.setUrl(url); googleSearchResultItem.setGsearchResultClass(GsearchResultClass); searchResults.add(googleSearchResultItem); } return searchResults; }
From source file:com.md87.charliebravo.commands.GoogleCommand.java
public void execute(final InputHandler handler, Response response, String line) throws MalformedURLException, IOException, JSONException { URL url = new URL("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=" + URLEncoder.encode(line, Charset.defaultCharset().name())); URLConnection connection = url.openConnection(); connection.addRequestProperty("Referer", "http://chris.smith.name/"); String input;/*from w w w . ja va 2 s . c o m*/ StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((input = reader.readLine()) != null) { builder.append(input); } JSONObject json = new JSONObject(builder.toString()); if (json.getInt("responseStatus") != 200) { throw new IOException(json.getString("responseDetails")); } if (json.getJSONObject("responseData").getJSONArray("results").length() == 0) { response.sendMessage("There were no results for '" + line + "'", true); } else { final JSONObject obj = json.getJSONObject("responseData").getJSONArray("results").getJSONObject(0); response.sendMessage("the first result for '" + line + "' is " + obj.getString("unescapedUrl") + ", titled '" + obj.getString("titleNoFormatting") + "'"); response.addFollowup(new DescriptionFollowup(obj)); response.addFollowup(new CacheFollowup(obj)); response.addFollowup( new NextFollowup(line, json.getJSONObject("responseData").getJSONArray("results"), 1)); } }
From source file:com.cnaude.purpleirc.Utilities.UpdateChecker.java
private String updateCheck(String mode) { String message;//from ww w.j a va2 s.c o m try { URL url = new URL("http://h.cnaude.org:8081/job/PurpleIRC-forge/lastStableBuild/api/json"); URLConnection conn = url.openConnection(); conn.setReadTimeout(5000); conn.addRequestProperty("User-Agent", "PurpleIRC-forge Update Checker"); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONObject obj = (JSONObject) JSONValue.parse(response); if (obj.isEmpty()) { return plugin.LOG_HEADER_F + " No files found, or Feed URL is bad."; } newVersion = obj.get("number").toString(); String downloadUrl = obj.get("url").toString(); plugin.logDebug("newVersionTitle: " + newVersion); newBuild = Integer.valueOf(newVersion); if (newBuild > currentBuild) { message = plugin.LOG_HEADER_F + " Latest dev build: " + newVersion + " is out!" + " You are still running build: " + currentVersion; message = message + plugin.LOG_HEADER_F + " Update at: " + downloadUrl; } else if (currentBuild > newBuild) { message = plugin.LOG_HEADER_F + " Dev build: " + newVersion + " | Current build: " + currentVersion; } else { message = plugin.LOG_HEADER_F + " No new version available"; } } catch (IOException | NumberFormatException e) { message = plugin.LOG_HEADER_F + " Error checking for latest dev build: " + e.getMessage(); } return message; }
From source file:org.eclipse.swordfish.tooling.ui.wizards.RegistryAccess.java
private Iterable<String> getWSDLUrls() throws IOException, SAXException { URLConnection urlConnection = registryUrl.openConnection(); urlConnection.addRequestProperty("accept", "application/xml"); InputStream is = urlConnection.getInputStream(); RegistryResponseParser parser = new RegistryResponseParser(); parser.parse(is);// w ww . j av a 2 s .c o m return parser.getUrls(); }
From source file:ca.etsmtl.applets.etsmobile.api.SignetBackgroundThread.java
@SuppressWarnings("unchecked") public T fetchObject() { T object = null;/*from w w w . j av a 2 s. c o m*/ try { final StringBuilder sb = new StringBuilder(); sb.append(urlStr); sb.append("/"); sb.append(action); final Gson gson = new Gson(); final String bodyParamsString = gson.toJson(bodyParams); final URL url = new URL(sb.toString()); final URLConnection conn = url.openConnection(); conn.addRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setDoOutput(true); final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(bodyParamsString); wr.flush(); final StringWriter writer = new StringWriter(); final InputStream in = conn.getInputStream(); IOUtils.copy(in, writer); in.close(); wr.close(); final String jsonString = writer.toString(); JSONObject jsonObject; jsonObject = new JSONObject(jsonString); JSONObject jsonRootArray; jsonRootArray = jsonObject.getJSONObject("d"); object = (T) gson.fromJson(jsonRootArray.toString(), typeOfClass); android.util.Log.d("JSON", jsonRootArray.toString()); } catch (final MalformedURLException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } catch (final JSONException e) { e.printStackTrace(); } return object; }
From source file:info.mallmc.framework.util.ProfileLoader.java
private void addProperties(GameProfile profile) { String uuid = getUUID(skinOwner); try {//from ww w .j ava 2 s . co m // Get the name from SwordPVP URL url = new URL( "https://sessionserver.mojang.com/session/minecraft/profile/" + uuid + "?unsigned=false"); URLConnection uc = url.openConnection(); uc.setUseCaches(false); uc.setDefaultUseCaches(false); uc.addRequestProperty("User-Agent", "Mozilla/5.0"); uc.addRequestProperty("Cache-Control", "no-cache, no-store, must-revalidate"); uc.addRequestProperty("Pragma", "no-cache"); // Parse it String json = new Scanner(uc.getInputStream(), "UTF-8").useDelimiter("\\A").next(); JSONParser parser = new JSONParser(); Object obj = parser.parse(json); JSONArray properties = (JSONArray) ((JSONObject) obj).get("properties"); for (int i = 0; i < properties.size(); i++) { try { JSONObject property = (JSONObject) properties.get(i); String name = (String) property.get("name"); String value = (String) property.get("value"); String signature = property.containsKey("signature") ? (String) property.get("signature") : null; if (signature != null) { profile.getProperties().put(name, new Property(name, value, signature)); } else { profile.getProperties().put(name, new Property(value, name)); } } catch (Exception e) { L.ogError(LL.ERROR, Trigger.LOAD, "Failed to apply auth property", "Failed to apply auth property"); } } } catch (Exception e) { ; // Failed to load skin } }
From source file:ca.etsmtl.applets.etsmobile.api.SignetBackgroundThread.java
@SuppressWarnings("unchecked") public T fetchArray() { ArrayList<E> array = new ArrayList<E>(); try {//from w w w . ja v a2 s .co m final StringBuilder sb = new StringBuilder(); sb.append(urlStr); sb.append("/"); sb.append(action); final Gson gson = new Gson(); final String bodyParamsString = gson.toJson(bodyParams); final URL url = new URL(sb.toString()); final URLConnection conn = url.openConnection(); conn.addRequestProperty("Content-Type", "application/json"); conn.addRequestProperty("charset", "utf-8"); conn.setDoOutput(true); final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(bodyParamsString); wr.flush(); final StringWriter writer = new StringWriter(); final InputStream in = conn.getInputStream(); IOUtils.copy(in, writer); in.close(); wr.close(); final String jsonString = writer.toString(); final ArrayList<E> objectList = new ArrayList<E>(); JSONObject jsonObject; jsonObject = new JSONObject(jsonString); JSONArray jsonRootArray; jsonRootArray = jsonObject.getJSONObject("d").getJSONArray(liste); android.util.Log.d("JSON", jsonRootArray.toString()); for (int i = 0; i < jsonRootArray.length(); i++) { objectList.add(gson.fromJson(jsonRootArray.getJSONObject(i).toString(), typeOfClass)); } array = objectList; } catch (final IOException e) { e.printStackTrace(); } catch (final JSONException e) { e.printStackTrace(); } return (T) array; }
From source file:org.manalith.ircbot.plugin.google.GooglePlugin.java
private int getGoogleCount(String keyword) { try {/*www . j a v a2s .c o m*/ // http://code.google.com/apis/websearch/docs/#fonje URL url = new URL("https://ajax.googleapis.com/ajax/services/search/web?v=1.0&" + "q=" + URLEncoder.encode(keyword, "UTF-8") + "&key=" + apiKey + "&userip=" + InetAddress.getLocalHost().getHostAddress()); URLConnection connection = url.openConnection(); connection.addRequestProperty("Referer", apiReferer); String line; StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { builder.append(line); } return Integer.parseInt(new JSONObject(builder.toString()).getJSONObject("responseData") .getJSONObject("cursor").getString("estimatedResultCount")); } catch (MalformedURLException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } catch (JSONException e) { logger.error(e.getMessage(), e); } return -1; }
From source file:org.fusesource.cloudmix.agent.FeatureList.java
private void load(URL url, String credentials) throws IOException { try {// w w w . j a v a2 s. co m URLConnection conn = url.openConnection(); if (credentials != null) { conn.addRequestProperty("Authorization", credentials); } System.out.println("URL is: " + url); InputStream is = conn.getInputStream(); features = new HashMap<String, Feature>(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document doc = factory.newDocumentBuilder().parse(is); NodeList nodes = doc.getDocumentElement().getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (!(node instanceof Element) || !"feature".equals(node.getNodeName())) { continue; } Element e = (Element) nodes.item(i); String name = e.getAttribute("name"); Feature f = new Feature(name, this); NodeList featureNodes = e.getElementsByTagName("feature"); for (int j = 0; j < featureNodes.getLength(); j++) { Element b = (Element) featureNodes.item(j); f.addDependency(b.getTextContent()); } NodeList configNodes = e.getElementsByTagName("config"); for (int j = 0; j < configNodes.getLength(); j++) { Element c = (Element) configNodes.item(j); String cfgName = c.getAttribute("name"); String data = c.getTextContent(); Properties properties = new Properties(); properties.load(new ByteArrayInputStream(data.getBytes())); f.addProperties(cfgName, properties); } NodeList bundleNodes = e.getElementsByTagName("bundle"); for (int j = 0; j < bundleNodes.getLength(); j++) { Element b = (Element) bundleNodes.item(j); f.addBundle(extractBundleInfo(b)); } features.put(name, f); } } catch (SAXException e) { throw (IOException) new IOException().initCause(e); } catch (ParserConfigurationException e) { throw (IOException) new IOException().initCause(e); } }
From source file:me.heyimblake.HiveMCRank.Utils.WebConnector.java
/** * Returns the Hive Name of the rank of a supplied UUID. Regular Member is returned if null. * * @param uuid the UUID of the player// w ww.j a va 2 s. c om * @return Hive Name of the rank of the UUID * @throws Exception thrown if the UUID has never been on TheHive or TheHive's API is not available. Default Rank is returned. */ public String getHiveRank(final UUID uuid) throws Exception { String rankfromapi; final String uuidNoDash = uuid.toString().replace("-", ""); try { final String API_URL = "http://api.hivemc.com/v1/player/"; final URLConnection connection = new URL(API_URL + uuidNoDash).openConnection(); Bukkit.getServer().getLogger().log(Level.INFO, "Connection opened to " + API_URL + uuidNoDash); connection.addRequestProperty("User-Agent", "Mozilla/5.0"); final JSONTokener tokener = new JSONTokener(connection.getInputStream()); final JSONObject root = new JSONObject(tokener); if (root.getString("rankName") == null) { rankfromapi = "Regular Member"; } else { rankfromapi = root.getString("rankName"); } } catch (Exception e) { Bukkit.getServer().getLogger().log(Level.SEVERE, "Exception occurred while trying to get the HiveMC rank of " + uuid); Bukkit.getServer().getLogger().log(Level.SEVERE, "Chances are that the user has never logged onto TheHive before. Their rank has been set to regular for now."); rankfromapi = "Regular Member"; } return rankfromapi; }