List of usage examples for java.net URLConnection addRequestProperty
public void addRequestProperty(String key, String value)
From source file:com.greatmancode.tools.utils.Updater.java
private boolean read() { try {//from w ww. j a v a2 s .c o m final URLConnection conn = this.url.openConnection(); conn.setConnectTimeout(5000); if (this.apiKey != null) { conn.addRequestProperty("X-API-Key", this.apiKey); } conn.addRequestProperty("User-Agent", "Updater (by Gravity)"); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) { caller.getLogger().warning("The updater could not find any files for the project id " + this.id); this.result = UpdateResult.FAIL_BADID; return false; } this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE); this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE); this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE); this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)) .get(Updater.VERSION_VALUE); return true; } catch (final IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { caller.getLogger() .warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); caller.getLogger().warning("Please double-check your configuration to ensure it is correct."); this.result = UpdateResult.FAIL_APIKEY; } else { caller.getLogger().warning("The updater could not contact dev.bukkit.org for updating."); caller.getLogger().warning( "If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); this.result = UpdateResult.FAIL_DBO; } e.printStackTrace(); return false; } }
From source file:com.adaptris.core.http.JdkHttpProducer.java
private void addHeaders(AdaptrisMessage msg, URLConnection c) { Properties p = getAdditionalHeaders(msg); for (Iterator i = p.keySet().iterator(); i.hasNext();) { String key = (String) i.next(); c.addRequestProperty(key, p.getProperty(key)); }/*from ww w .jav a 2 s . co m*/ // Bug#2555 // for (String key : p.stringPropertyNames()) { // c.addRequestProperty(key, p.getProperty(key)); // } }
From source file:eionet.gdem.utils.InputFile.java
/** * Opens URLConnection and reads the source into InputStream. * * @throws IOException in case the reading of InuptStream from URLConnection fails. *//* www. j a v a 2 s . com*/ private void fillInputStream() throws IOException { isClosed = false; URLConnection uc = url.openConnection(); ticket = getAuthentication(); uc.addRequestProperty("Accept", "*/*"); if (ticket != null) { // String auth = Utils.getEncodedAuthentication(user,pwd); uc.addRequestProperty("Authorization", " Basic " + ticket); } LOGGER.info("Start download file: " + url.toString()); this.inputStream = uc.getInputStream(); if (storeLocally) { tmpFileLocation = saveFileInLocalStorage("tmp"); isClosed = false; inputStream = new FileInputStream(tmpFileLocation); } }
From source file:com.quartercode.quarterbukkit.api.query.ServerModsAPIQuery.java
/** * Executes the stored query and returns the result as a {@link JSONArray}. * The query string ({@link #getQuery()}) is attached to {@code https://api.curseforge.com/servermods/}. * The GET response of that {@link URL} is then parsed to a {@link JSONArray}. * //from ww w. ja v a 2s. c o m * @return The response of the server mods api. * @throws QueryException Something goes wrong while querying the server mods api. */ public JSONArray execute() throws QueryException { // Build request url using the query URL requestUrl = null; try { requestUrl = new URL(HOST + query); } catch (MalformedURLException e) { throw new QueryException(QueryExceptionType.MALFORMED_URL, this, HOST + query, e); } // Open connection to request url URLConnection request = null; try { request = requestUrl.openConnection(); } catch (IOException e) { throw new QueryException(QueryExceptionType.CANNOT_OPEN_CONNECTION, this, requestUrl.toExternalForm(), e); } // Set connection timeout request.setConnectTimeout(CONNECTION_TIMEOUT); // Set user agent request.addRequestProperty("User-Agent", USER_AGENT); // Set api key (if provided) String apiKey = QuarterBukkit.getPlugin().getConfig().getString("server-mods-api-key"); if (apiKey != null && !apiKey.isEmpty()) { request.addRequestProperty("X-API-Key", apiKey); } // We want to read the results request.setDoOutput(true); // Read first line from the response BufferedReader reader = null; String response = null; try { reader = new BufferedReader(new InputStreamReader(request.getInputStream())); response = reader.readLine(); } catch (IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { throw new QueryException(QueryExceptionType.INVALID_API_KEY, this, requestUrl.toExternalForm(), e); } else { throw new QueryException(QueryExceptionType.CANNOT_READ_RESPONSE, this, requestUrl.toExternalForm(), e); } } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { throw new QueryException(QueryExceptionType.CANNOT_CLOSE_RESPONSE_STREAM, this, requestUrl.toExternalForm(), e); } } } // Parse the response Object jsonResponse = JSONValue.parse(response); if (jsonResponse instanceof JSONArray) { return (JSONArray) jsonResponse; } else { throw new QueryException(QueryExceptionType.INVALID_RESPONSE, this, requestUrl.toExternalForm()); } }
From source file:io.takari.maven.testing.executor.junit.MavenVersionResolver.java
private InputStream openStream(URL resource) throws IOException { URLConnection connection = resource.openConnection(); if (connection instanceof HttpURLConnection) { // for some reason, nexus version 2.11.1-01 returns partial maven-metadata.xml // unless request User-Agent header is set to non-default value connection.addRequestProperty("User-Agent", "takari-plugin-testing"); int responseCode = ((HttpURLConnection) connection).getResponseCode(); if (responseCode < 200 || responseCode > 299) { String message = String.format("HTTP/%d %s", responseCode, ((HttpURLConnection) connection).getResponseMessage()); throw responseCode == HttpURLConnection.HTTP_NOT_FOUND ? new FileNotFoundException(message) : new IOException(message); }/*from w w w . j a v a 2 s . c om*/ } return connection.getInputStream(); }
From source file:com.net.h1karo.sharecontrol.ShareControl.java
public void updateCheck() { String CBuildString = "", NBuildString = ""; int CMajor = 0, CMinor = 0, CMaintenance = 0, CBuild = 0, NMajor = 0, NMinor = 0, NMaintenance = 0, NBuild = 0;/* w w w . j a v a 2s .c om*/ try { URL url = new URL("https://api.curseforge.com/servermods/files?projectids=90354"); URLConnection conn = url.openConnection(); conn.setReadTimeout(5000); conn.addRequestProperty("User-Agent", "ShareControl Update Checker"); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) { this.getLogger().warning("No files found, or Feed URL is bad."); result = UpdateResult.ERROR; return; } String newVersionTitle = ((String) ((JSONObject) array.get(array.size() - 1)).get("name")); newVersion = newVersionTitle.replace("ShareControl v", "").trim(); /**\\**/ /**\\**//**\\**/ /**\ GET VERSIONS /**\ /**\\**/ /**\\**//**\\**/ String[] CStrings = currentVersion.split(Pattern.quote(".")); CMajor = Integer.parseInt(CStrings[0]); if (CStrings.length > 1) if (CStrings[1].contains("-")) { CMinor = Integer.parseInt(CStrings[1].split(Pattern.quote("-"))[0]); CBuildString = CStrings[1].split(Pattern.quote("-"))[1]; if (CBuildString.contains("b")) { beta = true; CBuildString = CBuildString.replace("b", ""); if (CBuildString != "") CBuild = Integer.parseInt(CBuildString) - 1; } else if (CBuildString.contains("a")) { alpha = true; CBuildString = CBuildString.replace("a", ""); if (CBuildString != "") CBuild = Integer.parseInt(CBuildString) - 10; } else CBuild = Integer.parseInt(CBuildString); } else { CMinor = Integer.parseInt(CStrings[1]); if (CStrings.length > 2) if (CStrings[2].contains("-")) { CMaintenance = Integer.parseInt(CStrings[2].split(Pattern.quote("-"))[0]); CBuildString = CStrings[2].split(Pattern.quote("-"))[1]; if (CBuildString.contains("b")) { beta = true; CBuildString = CBuildString.replace("b", ""); if (CBuildString != "") CBuild = Integer.parseInt(CBuildString) - 1; } else if (CBuildString.contains("a")) { alpha = true; CBuildString = CBuildString.replace("a", ""); if (CBuildString != "") CBuild = Integer.parseInt(CBuildString) - 10; } else CBuild = Integer.parseInt(CBuildString); } else CMaintenance = Integer.parseInt(CStrings[2]); } String[] NStrings = newVersion.split(Pattern.quote(".")); NMajor = Integer.parseInt(NStrings[0]); if (NStrings.length > 1) if (NStrings[1].contains("-")) { NMinor = Integer.parseInt(NStrings[1].split(Pattern.quote("-"))[0]); NBuildString = NStrings[1].split(Pattern.quote("-"))[1]; if (NBuildString.contains("b")) { beta = true; NBuildString = NBuildString.replace("b", ""); if (NBuildString != "") NBuild = Integer.parseInt(NBuildString) - 1; } else if (NBuildString.contains("a")) { alpha = true; NBuildString = NBuildString.replace("a", ""); if (NBuildString != "") NBuild = Integer.parseInt(NBuildString) - 10; } else NBuild = Integer.parseInt(NBuildString); } else { NMinor = Integer.parseInt(NStrings[1]); if (NStrings.length > 2) if (NStrings[2].contains("-")) { NMaintenance = Integer.parseInt(NStrings[2].split(Pattern.quote("-"))[0]); NBuildString = NStrings[2].split(Pattern.quote("-"))[1]; if (NBuildString.contains("b")) { beta = true; NBuildString = NBuildString.replace("b", ""); if (NBuildString != "") NBuild = Integer.parseInt(NBuildString) - 1; } else if (NBuildString.contains("a")) { alpha = true; NBuildString = NBuildString.replace("a", ""); if (NBuildString != "") NBuild = Integer.parseInt(NBuildString) - 10; } else NBuild = Integer.parseInt(NBuildString); } else NMaintenance = Integer.parseInt(NStrings[2]); } /**\\**/ /**\\**//**\\**/ /**\ CHECK VERSIONS /**\ /**\\**/ /**\\**//**\\**/ if ((CMajor < NMajor) || (CMajor == NMajor && CMinor < NMinor) || (CMajor == NMajor && CMinor == NMinor && CMaintenance < NMaintenance) || (CMajor == NMajor && CMinor == NMinor && CMaintenance == NMaintenance && CBuild < NBuild)) result = UpdateResult.UPDATE_AVAILABLE; else result = UpdateResult.NO_UPDATE; return; } catch (Exception e) { console.sendMessage(" There was an issue attempting to check for the latest version."); } result = UpdateResult.ERROR; }
From source file:de.static_interface.sinklibrary.Updater.java
private boolean isUpdateAvailable() { try {// w w w . j av a 2s . com final URLConnection conn = url.openConnection(); conn.setConnectTimeout(5000); String version = SinkLibrary.getInstance().getVersion(); conn.addRequestProperty("User-Agent", "SinkLibrary/v" + version + " (modified by Trojaner)"); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) { SinkLibrary.getInstance().getLogger() .warning("The updater could not find any files for the project id " + id); result = UpdateResult.FAIL_BADID; return false; } versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE); versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE); versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE); versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.VERSION_VALUE); return true; } catch (final IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { SinkLibrary.getInstance().getLogger() .warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); SinkLibrary.getInstance().getLogger() .warning("Please double-check your configuration to ensure it is correct."); result = UpdateResult.FAIL_APIKEY; } else { SinkLibrary.getInstance().getLogger() .warning("The updater could not contact dev.bukkit.org for updating."); SinkLibrary.getInstance().getLogger().warning( "If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); result = UpdateResult.FAIL_DBO; } e.printStackTrace(); return false; } }
From source file:eu.markov.jenkins.plugin.mvnmeta.MavenMetadataParameterDefinition.java
private MavenMetadataVersions getArtifactMetadata() { InputStream input = null;/*from ww w. j a va 2s . c o m*/ try { URL url = new URL(getArtifactUrlForPath("maven-metadata.xml")); LOGGER.finest("Requesting metadata from URL: " + url.toExternalForm()); URLConnection conn = url.openConnection(); if (StringUtils.isNotBlank(url.getUserInfo())) { LOGGER.finest("Using implicit UserInfo"); String encodedAuth = new String(Base64.encodeBase64(url.getUserInfo().getBytes(UTF8)), UTF8); conn.addRequestProperty("Authorization", "Basic " + encodedAuth); } if (StringUtils.isNotBlank(this.username) && StringUtils.isNotBlank(this.password)) { LOGGER.finest("Using explicit UserInfo"); String userpassword = username + ":" + password; String encodedAuthorization = new String(Base64.encodeBase64(userpassword.getBytes(UTF8)), UTF8); conn.addRequestProperty("Authorization", "Basic " + encodedAuthorization); } input = conn.getInputStream(); JAXBContext context = JAXBContext.newInstance(MavenMetadataVersions.class); Unmarshaller unmarshaller = context.createUnmarshaller(); MavenMetadataVersions metadata = (MavenMetadataVersions) unmarshaller.unmarshal(input); if (sortOrder == SortOrder.DESC) { Collections.reverse(metadata.versioning.versions); } metadata.versioning.versions = filterVersions(metadata.versioning.versions); return metadata; } catch (Exception e) { LOGGER.log(Level.WARNING, "Could not parse maven-metadata.xml", e); MavenMetadataVersions result = new MavenMetadataVersions(); result.versioning.versions.add("<" + e.getClass().getName() + ": " + e.getMessage() + ">"); return result; } finally { try { if (input != null) input.close(); } catch (IOException e) { // ignore } } }
From source file:edu.ucuenca.authorsrelatedness.Distance.java
public synchronized String Http(String s) throws SQLException, IOException { String get = Cache.getInstance().get(s); String resp = ""; if (get != null) { //System.out.print("."); resp = get;// w w w .j a v a2 s . c o m } else { final URL url = new URL(s); final URLConnection connection = url.openConnection(); connection.setConnectTimeout(60000); connection.setReadTimeout(60000); connection.addRequestProperty("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0"); connection.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); final Scanner reader = new Scanner(connection.getInputStream(), "UTF-8"); while (reader.hasNextLine()) { final String line = reader.nextLine(); resp += line + "\n"; } reader.close(); Cache.getInstance().put(s, resp); } return resp; }
From source file:io.github.bonigarcia.wdm.BrowserManager.java
protected InputStream openGitHubConnection(URL driverUrl) throws IOException { Proxy proxy = createProxy();//from w w w.j a v a2 s . co m URLConnection conn = proxy != null ? driverUrl.openConnection(proxy) : driverUrl.openConnection(); conn.setRequestProperty("User-Agent", "Mozilla/5.0"); conn.addRequestProperty("Connection", "keep-alive"); String gitHubTokenName = WdmConfig.getString("wdm.gitHubTokenName"); String gitHubTokenSecret = WdmConfig.getString("wdm.gitHubTokenSecret"); if (!isNullOrEmpty(gitHubTokenName) && !isNullOrEmpty(gitHubTokenSecret)) { String userpass = gitHubTokenName + ":" + gitHubTokenSecret; String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes())); conn.setRequestProperty("Authorization", basicAuth); } conn.connect(); return conn.getInputStream(); }