List of usage examples for java.net HttpURLConnection getInputStream
public InputStream getInputStream() throws IOException
From source file:Main.java
public static String doGet(String urlStr) { URL url = null;/* www . j a v a 2 s . c om*/ HttpURLConnection conn = null; InputStream is = null; ByteArrayOutputStream baos = null; try { url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIMEOUT_IN_MILLIONS); conn.setConnectTimeout(TIMEOUT_IN_MILLIONS); conn.setRequestMethod("GET"); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); if (conn.getResponseCode() == 200) { is = conn.getInputStream(); baos = new ByteArrayOutputStream(); int len = -1; byte[] buf = new byte[128]; while ((len = is.read(buf)) != -1) { baos.write(buf, 0, len); } baos.flush(); return baos.toString(); } else { throw new RuntimeException(" responseCode is not 200 ... "); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (baos != null) baos.close(); } catch (IOException e) { } conn.disconnect(); } return null; }
From source file:org.apache.brooklyn.util.http.HttpTool.java
/** * Consumes the input stream entirely and then cleanly closes the connection. * Ignores all exceptions completely, not even logging them! * * Consuming the stream fully is useful for preventing idle TCP connections. * @see <a href="http://docs.oracle.com/javase/8/docs/technotes/guides/net/http-keepalive.html">Persistent Connections</a> *//*from w w w . j a v a 2 s.com*/ public static void consumeAndCloseQuietly(HttpURLConnection connection) { try { Streams.readFully(connection.getInputStream()); } catch (Exception e) { } closeQuietly(connection); }
From source file:com.blogspot.ryanfx.auth.GoogleUtil.java
/** * Sends the auth token to google and gets the json result. * @param token auth token/*from w ww . ja v a2 s . c om*/ * @return json result if valid request, null if invalid. * @throws IOException * @throws LoginException */ private static String issueTokenGetRequest(String token) throws IOException, LoginException { int timeout = 2000; URL u = new URL("https://www.googleapis.com/oauth2/v2/userinfo"); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setRequestProperty("Content-length", "0"); c.setRequestProperty("Authorization", "OAuth " + token); c.setUseCaches(false); c.setAllowUserInteraction(false); c.setConnectTimeout(timeout); c.setReadTimeout(timeout); c.connect(); int status = c.getResponseCode(); if (status == HttpServletResponse.SC_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); return sb.toString(); } else if (status == HttpServletResponse.SC_UNAUTHORIZED) { Logger.getLogger(GoogleUtil.class.getName()).severe("Invalid token request: " + token); } return null; }
From source file:Main.java
public static byte[] doGet(String urlStr) { URL url = null;//from ww w . jav a 2 s. co m HttpURLConnection conn = null; InputStream is = null; ByteArrayOutputStream baos = null; try { url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIMEOUT_IN_MILLIONS); conn.setConnectTimeout(TIMEOUT_IN_MILLIONS); conn.setRequestMethod("GET"); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); if (conn.getResponseCode() == 200) { is = conn.getInputStream(); baos = new ByteArrayOutputStream(); int len = -1; byte[] buf = new byte[128]; while ((len = is.read(buf)) != -1) { baos.write(buf, 0, len); } baos.flush(); return baos.toByteArray(); } else { throw new RuntimeException(" responseCode is not 200 ... "); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (baos != null) baos.close(); } catch (IOException e) { } conn.disconnect(); } return null; }
From source file:com.machinepublishers.jbrowserdriver.StreamConnectionClient.java
private static SSLContext sslContext() { final String property = SettingsManager.settings().ssl(); if (property != null && !property.isEmpty() && !"null".equals(property)) { if ("trustanything".equals(property)) { try { return SSLContexts.custom().loadTrustMaterial(KeyStore.getInstance(KeyStore.getDefaultType()), new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; }/*from w ww. ja va2 s. c o m*/ }).build(); } catch (Throwable t) { LogsServer.instance().exception(t); } } else { try { String location = property; location = location.equals("compatible") ? "https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt" : location; File cachedPemFile = new File("./pemfile_cached"); boolean remote = location.startsWith("https://") || location.startsWith("http://"); if (remote && cachedPemFile.exists() && (System.currentTimeMillis() - cachedPemFile.lastModified() < 48 * 60 * 60 * 1000)) { location = cachedPemFile.getAbsolutePath(); remote = false; } String pemBlocks = null; if (remote) { HttpURLConnection remotePemFile = (HttpURLConnection) StreamHandler .defaultConnection(new URL(location)); remotePemFile.setRequestMethod("GET"); remotePemFile.connect(); pemBlocks = Util.toString(remotePemFile.getInputStream(), Util.charset(remotePemFile)); cachedPemFile.delete(); Files.write(Paths.get(cachedPemFile.getAbsolutePath()), pemBlocks.getBytes("utf-8")); } else { pemBlocks = new String(Files.readAllBytes(Paths.get(new File(location).getAbsolutePath())), "utf-8"); } KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Matcher matcher = pemBlock.matcher(pemBlocks); boolean found = false; while (matcher.find()) { String pemBlock = matcher.group(1).replaceAll("[\\n\\r]+", ""); ByteArrayInputStream byteStream = new ByteArrayInputStream( Base64.getDecoder().decode(pemBlock)); java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) cf .generateCertificate(byteStream); String alias = cert.getSubjectX500Principal().getName("RFC2253"); if (alias != null && !keyStore.containsAlias(alias)) { found = true; keyStore.setCertificateEntry(alias, cert); } } if (found) { KeyManagerFactory keyManager = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManager.init(keyStore, null); TrustManagerFactory trustManager = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManager.init(keyStore); SSLContext context = SSLContext.getInstance("TLS"); context.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null); return context; } } catch (Throwable t) { LogsServer.instance().exception(t); } } } return SSLContexts.createSystemDefault(); }
From source file:outfox.dict.contest.util.FileUtils.java
/** * ??/*from ww w .j a v a 2s . com*/ * @param downloadUrl * @return */ public static byte[] getbytesFromURL(String downloadUrl) { HttpURLConnection httpUrl = null; ByteArrayOutputStream out = null; byte[] byteArray = null; InputStream in = null; try { // URL url = new URL(downloadUrl); httpUrl = (HttpURLConnection) url.openConnection(); // ? httpUrl.connect(); // ?? in = httpUrl.getInputStream(); out = new ByteArrayOutputStream(); byte[] b = new byte[4096]; int n; while ((n = in.read(b)) != -1) { out.write(b, 0, n); } byteArray = out.toByteArray(); in.close(); out.close(); httpUrl.disconnect(); } catch (Exception e) { LOG.error("FileUtils.getBytesFromURL error...", e); } return byteArray; }
From source file:fr.haploid.webservices.WebServicesHelper.java
protected static synchronized WebServicesResponseData downloadFromServer(String url, JSONObject params, String type) {//from ww w . j ava2 s. co m int responseCode = 9999; StringBuffer buffer = new StringBuffer(); Uri.Builder builder = new Uri.Builder(); builder.encodedPath(url); JSONArray namesOfParams = params.names(); for (int i = 0; i < namesOfParams.length(); i++) { try { String param = namesOfParams.getString(i); builder.appendQueryParameter(param, params.get(param).toString()); } catch (JSONException e) { return new WebServicesResponseData("JSONException " + e.toString(), responseCode, false); } } URL urlBuild; try { urlBuild = new URL(builder.build().toString()); } catch (MalformedURLException e) { return new WebServicesResponseData("MalformedURLException " + e.toString(), responseCode, false); } try { HttpURLConnection urlConnection = (HttpURLConnection) urlBuild.openConnection(); try { urlConnection.setRequestMethod(type); } catch (ProtocolException e) { return new WebServicesResponseData("ProtocolException " + e.toString(), responseCode, false); } urlConnection.connect(); responseCode = urlConnection.getResponseCode(); if (responseCode < 400) { InputStream inputStream = urlConnection.getInputStream(); if (inputStream == null) { return new WebServicesResponseData(null, responseCode, false); } BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { buffer.append(line + "\n"); } if (buffer.length() == 0) { return new WebServicesResponseData(null, responseCode, false); } } } catch (IOException e) { return new WebServicesResponseData("IOException " + e.toString(), responseCode, false); } return new WebServicesResponseData(buffer.toString(), responseCode, true); }
From source file:javaphpmysql.JavaPHPMySQL.java
public static void sendGet() { //Creamos un objeto JSON JSONObject jsonObj = new JSONObject(); //Aadimos el nombre, apellidos y email del usuario jsonObj.put("nombre", nombre); jsonObj.put("apellidos", apellidos); jsonObj.put("email", email); //Creamos una lista para almacenar el JSON List l = new LinkedList(); l.addAll(Arrays.asList(jsonObj)); //Generamos el String JSON String jsonString = JSONValue.toJSONString(l); System.out.println("JSON GENERADO:"); System.out.println(jsonString); System.out.println(""); try {//from w ww. j a v a2 s . c o m //Codificar el json a URL jsonString = URLEncoder.encode(jsonString, "UTF-8"); //Generar la URL String url = SERVER_PATH + "listenGet.php?json=" + jsonString; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); //add request header con.setRequestProperty("User-Agent", USER_AGENT); int responseCode = con.getResponseCode(); System.out.println("\nSending 'GET' request to URL : " + url); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result System.out.println(response.toString()); } catch (Exception e) { e.printStackTrace(); } }
From source file:Main.java
public static JSONObject updateRequest(String query) { HttpURLConnection connection = null; try {//from w w w . ja va 2 s . co m connection = (HttpURLConnection) new URL(url + query).openConnection(); connection.setRequestMethod("PUT"); connection.setRequestProperty("Accept-Charset", charset); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write("Resource content"); out.close(); statusCode = connection.getResponseCode(); if (statusCode != 200) { return null; } InputStream response = connection.getInputStream(); BufferedReader bR = new BufferedReader(new InputStreamReader(response)); String line = ""; StringBuilder responseStrBuilder = new StringBuilder(); while ((line = bR.readLine()) != null) { responseStrBuilder.append(line); } response.close(); return new JSONObject(responseStrBuilder.toString()); } catch (IOException | JSONException e) { e.printStackTrace(); } return new JSONObject(); }
From source file:com.company.project.core.connector.HttpClientHelper.java
public static String getResponseStringFromConn(HttpURLConnection conn, String payLoad) throws IOException { // Send the http message payload to the server. if (payLoad != null) { conn.setDoOutput(true);// w ww .j a v a 2s.c o m OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream()); osw.write(payLoad); osw.flush(); osw.close(); } // Get the message response from the server. BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = ""; StringBuffer stringBuffer = new StringBuffer(); while ((line = br.readLine()) != null) { stringBuffer.append(line); } br.close(); return stringBuffer.toString(); }