List of usage examples for java.net HttpURLConnection connect
public abstract void connect() throws IOException;
From source file:org.apache.hadoop.mapreduce.v2.app.webapp.TestAMWebApp.java
@Test public void testMRWebAppRedirection() throws Exception { String[] schemePrefix = { WebAppUtils.HTTP_PREFIX, WebAppUtils.HTTPS_PREFIX }; for (String scheme : schemePrefix) { MRApp app = new MRApp(2, 2, true, this.getClass().getName(), true) { @Override// w w w . j a v a2s . c o m protected ClientService createClientService(AppContext context) { return new MRClientService(context); } }; Configuration conf = new Configuration(); conf.set(YarnConfiguration.PROXY_ADDRESS, "9.9.9.9"); conf.set(YarnConfiguration.YARN_HTTP_POLICY_KEY, scheme.equals(WebAppUtils.HTTPS_PREFIX) ? Policy.HTTPS_ONLY.name() : Policy.HTTP_ONLY.name()); webProxyBase = "/proxy/" + app.getAppID(); conf.set("hadoop.http.filter.initializers", TestAMFilterInitializer.class.getName()); Job job = app.submit(conf); String hostPort = NetUtils .getHostPortString(((MRClientService) app.getClientService()).getWebApp().getListenerAddress()); URL httpUrl = new URL("http://" + hostPort + "/mapreduce"); HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection(); conn.setInstanceFollowRedirects(false); conn.connect(); String expectedURL = scheme + conf.get(YarnConfiguration.PROXY_ADDRESS) + ProxyUriUtils.getPath(app.getAppID(), "/mapreduce"); Assert.assertEquals(expectedURL, conn.getHeaderField(HttpHeaders.LOCATION)); Assert.assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, conn.getResponseCode()); app.waitForState(job, JobState.SUCCEEDED); app.verifyCompleted(); } }
From source file:com.mp3tunes.android.player.RemoteAlbumArtHandler.java
private Bitmap getArtwork(Track t) { String urlstr = null;//w ww . j av a 2s . c o m InputStream is = null; String file = getArtFile(t); if (file != null) { try { is = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } } else { try { urlstr = getArtUrl(t); URL url = new URL(urlstr); HttpURLConnection c = (HttpURLConnection) url.openConnection(); c.setDoInput(true); c.connect(); is = c.getInputStream(); } catch (MalformedURLException e) { Log.d("RemoteImageHandler", "RemoteImageWorker passed invalid URL: " + urlstr); } catch (IOException e) { } } if (is == null) return null; Bitmap img; img = BitmapFactory.decodeStream(is); return img; }
From source file:com.screenslicer.common.CommonUtil.java
public static void postQuickly(String uri, String recipient, String postData) { HttpURLConnection conn = null; try {//from ww w. j av a2 s . c om postData = Crypto.encode(postData, recipient); conn = (HttpURLConnection) new URL(uri).openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); conn.setRequestProperty("Content-Type", "application/json"); byte[] bytes = postData.getBytes("utf-8"); conn.setRequestProperty("Content-Length", String.valueOf(bytes.length)); OutputStream os = conn.getOutputStream(); os.write(bytes); conn.connect(); Crypto.decode(IOUtils.toString(conn.getInputStream(), "utf-8"), recipient); } catch (Exception e) { Log.exception(e); } }
From source file:com.tc.util.io.ServerURL.java
public String getServerVersion(PwProvider pwProvider) throws IOException { for (int i = 0; i < 3; i++) { HttpURLConnection urlConnection = createSecureConnection(pwProvider); try {/*from ww w. j ava 2 s . c o m*/ urlConnection.connect(); int responseCode = urlConnection.getResponseCode(); if (responseCode == 200) { return urlConnection.getHeaderField(VERSION_HEADER); } else { logger.info("Failed to retrieve header field, response code : " + responseCode + ", headers :\n" + readHeaderFields(urlConnection) + " body : \n[" + readLines(urlConnection) + "]"); } } finally { urlConnection.disconnect(); } logger.info("Retrying connection since response code != 200"); ThreadUtil.reallySleep(50); } throw new IOException( "Cannot retrieve " + VERSION_HEADER + " header from server url after 3 tries : " + theURL); }
From source file:it.evilsocket.dsploit.net.GemParser.java
private void fetch() throws JSONException, IOException { HttpURLConnection connection = null; BufferedReader reader = null; try {/*from w w w . j a v a 2 s .c o m*/ HttpURLConnection.setFollowRedirects(true); connection = (HttpURLConnection) (new URL(mUrl)).openConnection(); connection.connect(); int ret = connection.getResponseCode(); if (ret != 200) throw new IOException("cannot retrieve remote json: " + ret); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) sb.append(line); JSONArray jGems = new JSONArray(sb.toString()); mGems = new RemoteGemInfo[jGems.length()]; for (int i = 0; i < jGems.length(); i++) { JSONObject gem = jGems.getJSONObject(i); mGems[i] = new RemoteGemInfo(gem.getString("name"), gem.getString("version"), (new DateTime(gem.getString("uploaded"))).toDate()); } } finally { if (reader != null) reader.close(); if (connection != null) connection.disconnect(); } }
From source file:fr.ybonnel.simpleweb4j.util.SimpleWebTestUtil.java
public UrlResponse doMethod(String requestMethod, String path, String body) throws Exception { URL url = new URL("http://localhost:" + port + path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(requestMethod); if (body != null) { connection.setDoOutput(true);/* w w w. j ava 2s.co m*/ connection.getOutputStream().write(body.getBytes()); } connection.connect(); UrlResponse response = new UrlResponse(); response.status = connection.getResponseCode(); response.headers = connection.getHeaderFields(); response.contentType = connection.getContentType(); if (response.status >= 400) { if (connection.getErrorStream() != null) { response.body = IOUtils.toString(connection.getErrorStream()); } } else { if (connection.getInputStream() != null) { response.body = IOUtils.toString(connection.getInputStream()); } } return response; }
From source file:myClass_Main.java
/** * * @param request// w w w . j a v a 2 s . c om * @param response * @throws ServletException * @throws IOException */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int option = Integer.parseInt(request.getParameter("optionValue")); String url; // do some processing here... // get response writer switch (option) { case 1: { int userValue = Integer.parseInt(request.getParameter("userValue")); String htmlres = ""; // build HTML code for (int i = 0; i < userValue; i++) { htmlres = htmlres + "<input type=\"text\" id=\"inputValue\" name=\"inputValue\" class=\"form-group form-control\" placeholder=\"Nombre de Pais " + (i + 1) + "\" required autofocus>"; } request.setAttribute("htmlres", htmlres); url = "/myPage_core.jsp"; ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(request, response); } break; case 2: { String[] input = request.getParameterValues("inputValue"); String sourceURL = "http://api.myjson.com/bins/vcv1"; //just a string // Connect to the URL using java's native library URL urlobject = new URL(sourceURL); HttpURLConnection conection = (HttpURLConnection) urlobject.openConnection(); conection.connect(); // Convert to a JSON object to print data String[][] contry_values = new String[10][input.length]; String zipcode = null; JSONParser jp = new JSONParser(); //from gson JSONObject root = null; JSONArray root_array = null; try { root = (JSONObject) jp.parse(new InputStreamReader(conection.getInputStream())); //Convert the input stream to a json element } catch (ParseException ex) { Logger.getLogger(myClass_Main.class.getName()).log(Level.SEVERE, null, ex); } boolean firstName = (boolean) root.containsKey("countries"); root = (JSONObject) root.get("countries"); root_array = (JSONArray) root.get("country"); //Iterator j = root_array.iterator(); for (int i = 0; i < input.length; i++) { Iterator j = root_array.iterator(); while (j.hasNext()) { JSONObject inner = (JSONObject) j.next(); if (inner.containsValue(input[i])) { contry_values[0][i] = (String) inner.get("isoNumeric"); contry_values[1][i] = (String) inner.get("countryName"); contry_values[2][i] = (String) inner.get("continentName"); contry_values[3][i] = (String) inner.get("capital"); contry_values[4][i] = (String) inner.get("languages"); if (contry_values[4][i].length() > 11) { String strOut = contry_values[4][i]; String trimedstring = strOut.substring(0, 10) + "...";// count start in 0 and 8 is excluded contry_values[4][i] = trimedstring; } contry_values[5][i] = (String) inner.get("population"); contry_values[6][i] = (String) inner.get("areaInSqKm"); contry_values[7][i] = (String) inner.get("countryCode"); contry_values[8][i] = "https://es.wikipedia.org/wiki/" + ((String) inner.get("countryName")); } } } System.out.println("The first name is: " + zipcode); request.setAttribute("firstname", zipcode); String htmlres = "<table class=\"table\">\n" + "<caption>Datos de Paises</caption>\n" + "<thead>\n" + "<tr>\n" + "<th>COD INT.</th>\n" + "<th>AVB.</th>\n" + "<th>Nombre</th>\n" + "<th>Continente</th>\n" + "<th>Capital</th>\n" + "<th>Idioma</th>\n" + "<th>Poblacion</th>\n" + "<th>Area km2</th>\n" + "<th>Wiki URL</th>\n" + "</tr>\n" + "</thead>\n" + "<tbody>"; // build HTML code for (int h = 0; h < input.length; h++) { if ((contry_values[0][h]) != null) { htmlres = htmlres + "<tr><th scope=\"row\">" + contry_values[0][h] + "</th>"; for (int g = 0; g < 9; g++) { if (g != 8) { htmlres = htmlres + "<td>" + contry_values[g][h] + "</td>"; } else { htmlres = htmlres + "<td>" + "<a href=\"" + contry_values[g][h] + "\" class=\"btn btn-info\" role=\"button\">" + contry_values[7][h] + "</a>" + "</td>"; } } htmlres = htmlres + "</tr>"; } else { htmlres = htmlres + "<tr><th scope=\"row\">" + "#Er." + h + "</th>"; htmlres = htmlres + "<td colspan=\"9\">" + "El pais \"" + input[h] + "\" no esta en la BD, verifique que el nombre esta en ingls, e intente de nuevo" + "</td>"; } } htmlres = htmlres + "<tr>"; htmlres = htmlres + "</tbody>\n" + "</table>"; request.setAttribute("htmlres", htmlres); url = "/myPage_res.jsp"; ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(request, response); } break; case 3: { url = "/index.jsp"; ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(request, response); } break; default: { url = "/index.jsp"; ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(request, response); } break; } }
From source file:net.ae97.pokebot.extensions.scrolls.ScrollCommand.java
@Override public void runEvent(CommandEvent event) { if (event.getArgs().length == 0) { event.respond("Usage: .scroll [name]"); return;/*w w w.j a v a2s. c om*/ } try { URL playerURL = new URL(url.replace("{name}", StringUtils.join(event.getArgs(), "%20"))); List<String> lines = new LinkedList<>(); HttpURLConnection conn = (HttpURLConnection) playerURL.openConnection(); conn.setRequestProperty("User-Agent", "PokeBot - " + PokeBot.VERSION); conn.connect(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { lines.add(line); } } JsonParser parser = new JsonParser(); JsonElement element = parser.parse(StringUtils.join(lines, "\n")); JsonObject obj = element.getAsJsonObject(); String result = obj.get("msg").getAsString(); if (!result.equalsIgnoreCase("success")) { event.respond("Scroll not found"); return; } JsonObject dataObject = obj.get("data").getAsJsonArray().get(0).getAsJsonObject(); StringBuilder builder = new StringBuilder(); builder.append(dataObject.get("name").getAsString()).append(" - "); builder.append("Cost: "); if (dataObject.get("costgrowth").getAsInt() > 0) { builder.append(dataObject.get("costgrowth").getAsInt()).append(" Growth"); } else if (dataObject.get("costorder").getAsInt() > 0) { builder.append(dataObject.get("costorder").getAsInt()).append(" Order"); } else if (dataObject.get("costenergy").getAsInt() > 0) { builder.append(dataObject.get("costenergy").getAsInt()).append(" Energy"); } else if (dataObject.get("costdecay").getAsInt() > 0) { builder.append(dataObject.get("costdecay").getAsInt()).append(" Decay"); } else { builder.append("0"); } builder.append(" - "); String kind = dataObject.get("kind").getAsString(); kind = Character.toUpperCase(kind.charAt(0)) + kind.substring(1).toLowerCase(); builder.append("Kind: ").append(kind).append(" - "); Rarity rarity = Rarity.get(dataObject.get("rarity").getAsInt()); String rarityString = rarity.name().toLowerCase(); rarityString = Character.toUpperCase(rarityString.charAt(0)) + rarityString.substring(1); builder.append("Rarity: ").append(rarityString); if (kind.equalsIgnoreCase("creature") || kind.equalsIgnoreCase("structure")) { builder.append(" - "); builder.append("Types: ").append(dataObject.get("types").getAsString()).append(" - "); builder.append("Attack: ").append(dataObject.get("ap").getAsInt()).append(" - "); builder.append("Cooldown: ").append(dataObject.get("ac").getAsInt()).append(" - "); builder.append("Health: ").append(dataObject.get("hp").getAsInt()); } builder.append("\n"); builder.append("Description: '").append(dataObject.get("description").getAsString()).append("' - "); builder.append("Flavor: '").append(dataObject.get("flavor").getAsString()).append("'"); String[] message = builder.toString().split("\n"); for (String msg : message) { event.respond("" + msg); } } catch (IOException | JsonSyntaxException | IllegalStateException ex) { PokeBot.getLogger().log(Level.SEVERE, "Error on getting scroll for Scrolls for '" + StringUtils.join(event.getArgs(), " ") + "'", ex); event.respond("Error on getting scroll: " + ex.getLocalizedMessage()); } }
From source file:net.gcolin.simplerepo.test.AbstractRepoTest.java
protected int getStatus(String url, long lastUpdate) throws IOException { HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection(); try {/*from w w w . java 2s .c om*/ if (lastUpdate > 0) { c.setIfModifiedSince(lastUpdate); } c.setUseCaches(false); c.connect(); return c.getResponseCode(); } finally { c.disconnect(); } }
From source file:net.gcolin.simplerepo.test.AbstractRepoTest.java
protected String getContent(String url, long lastUpdate) throws IOException { HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection(); try {//from w w w.j ava 2 s . c o m if (lastUpdate > 0) { c.setIfModifiedSince(lastUpdate); } c.setUseCaches(false); c.connect(); return c.getResponseCode() == HttpURLConnection.HTTP_OK ? new String(IOUtils.toByteArray(c.getInputStream()), "utf-8") : null; } finally { c.disconnect(); } }