List of usage examples for java.net HttpURLConnection getInputStream
public InputStream getInputStream() throws IOException
From source file:core.Utility.java
public static ArrayList<String> getWikiText(String _word) throws MalformedURLException, IOException { ArrayList<String> _list = new ArrayList(); try {/*from www . j a v a 2 s . com*/ URL url = new URL("http://en.wiktionary.org/w/api.php" + "?action=parse" + "&prop=wikitext" + "&page=" + _word + "&format=xmlfm"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output, wikiText = ""; while ((output = br.readLine()) != null) { wikiText += output + "\n"; } conn.disconnect(); } catch (MalformedURLException e) { throw e; } catch (IOException e) { throw e; } return _list; }
From source file:Main.java
/** * On some devices we have to hack:// w w w .ja v a2 s.c o m * http://developers.sun.com/mobility/reference/techart/design_guidelines/http_redirection.html * @return the resolved url if any. Or null if it couldn't resolve the url * (within the specified time) or the same url if response code is OK */ public static String getResolvedUrl(String urlAsString, int timeout) { try { URL url = new URL(urlAsString); //using proxy may increase latency HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); // force no follow hConn.setInstanceFollowRedirects(false); // the program doesn't care what the content actually is !! // http://java.sun.com/developer/JDCTechTips/2003/tt0422.html hConn.setRequestMethod("HEAD"); // default is 0 => infinity waiting hConn.setConnectTimeout(timeout); hConn.setReadTimeout(timeout); hConn.connect(); int responseCode = hConn.getResponseCode(); hConn.getInputStream().close(); if (responseCode == HttpURLConnection.HTTP_OK) return urlAsString; String loc = hConn.getHeaderField("Location"); if (responseCode == HttpURLConnection.HTTP_MOVED_PERM && loc != null) return loc.replaceAll(" ", "+"); } catch (Exception ex) { } return ""; }
From source file:com.cyphermessenger.client.SyncRequest.java
public static void sendMessage(CypherSession session, CypherUser contactUser, CypherMessage message) throws IOException, APIErrorException { CypherUser user = session.getUser(); byte[] timestampBytes = Utils.longToBytes(message.getTimestamp()); int messageIDLong = message.getMessageID(); Encrypt encryptionCtx = new Encrypt(user.getKey().getSharedSecret(contactUser.getKey())); encryptionCtx.updateAuthenticatedData(Utils.longToBytes(messageIDLong)); encryptionCtx.updateAuthenticatedData(timestampBytes); byte[] payload; try {/* ww w. jav a 2 s . c o m*/ payload = encryptionCtx.process(message.getText().getBytes()); } catch (InvalidCipherTextException e) { throw new RuntimeException(e); } HashMap<String, String> pairs = new HashMap<>(6); pairs.put("payload", Utils.BASE64_URL.encode(payload)); pairs.put("contactID", contactUser.getUserID() + ""); pairs.put("messageID", messageIDLong + ""); pairs.put("messageTimestamp", message.getTimestamp() + ""); pairs.put("userKeyTimestamp", session.getUser().getKeyTime() + ""); pairs.put("contactKeyTimestamp", contactUser.getKeyTime() + ""); HttpURLConnection conn = doRequest("message", session, pairs); if (conn.getResponseCode() != 200) { throw new IOException("Server error"); } InputStream in = conn.getInputStream(); JsonNode node = MAPPER.readTree(in); conn.disconnect(); int statusCode = node.get("status").asInt(); if (statusCode != StatusCode.OK) { throw new APIErrorException(statusCode); } }
From source file:com.linkedin.pinot.controller.helix.ControllerTest.java
public static String sendPutRequest(String urlString, String payload) throws IOException { LOGGER.info("Sending PUT to " + urlString + " with payload " + payload); final long start = System.currentTimeMillis(); final URL url = new URL(urlString); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true);// w w w.j a va 2 s .com conn.setRequestMethod("PUT"); final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8")); writer.write(payload, 0, payload.length()); writer.flush(); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); final StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } final long stop = System.currentTimeMillis(); LOGGER.info(" Time take for Request : " + urlString + " in ms:" + (stop - start)); return sb.toString(); }
From source file:com.android.dialer.omni.PlaceUtil.java
/** * Executes a post request and return a JSON object * @param url The API URL// www. j ava2 s . c om * @param data The data to post in POST field * @return the JSON object * @throws IOException * @throws JSONException */ public static JSONObject postJsonRequest(String url, String postData) throws IOException, JSONException { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); if (DEBUG) Log.d(TAG, "Posting: " + postData + " to " + url); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(postData); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONObject json = new JSONObject(response.toString()); return json; }
From source file:com.cyphermessenger.client.SyncRequest.java
public static List<String> findUser(CypherSession session, String username, int limit) throws IOException, APIErrorException { String[] keys = new String[] { "username", "limit" }; String[] vals = new String[] { username, limit + "" }; HttpURLConnection conn = doRequest("find", session, keys, vals); if (conn.getResponseCode() != 200) { throw new IOException("Server error"); }/*from w w w.j av a 2 s. com*/ JsonNode node = MAPPER.readTree(conn.getInputStream()); conn.disconnect(); int statusCode = node.get("status").asInt(); if (statusCode != StatusCode.OK) { throw new APIErrorException(statusCode); } else { return Utils.MAPPER.treeToValue(node.get("users"), ArrayList.class); } }
From source file:com.cyphermessenger.client.SyncRequest.java
public static CypherUser registerUser(String username, String password, String captchaValue, Captcha captcha) throws IOException, APIErrorException { if (!captcha.verify(captchaValue)) { throw new APIErrorException(StatusCode.CAPTCHA_INVALID); }//from w w w . j a v a 2 s . c o m username = username.toLowerCase(); captchaValue = captchaValue.toLowerCase(); byte[] serverPassword = Utils.cryptPassword(password.getBytes(), username); byte[] localPassword = Utils.sha256(password); String serverPasswordEncoded = Utils.BASE64_URL.encode(serverPassword); ECKey key = new ECKey(); byte[] publicKey = key.getPublicKey(); byte[] privateKey = key.getPrivateKey(); try { privateKey = Encrypt.process(localPassword, privateKey); } catch (InvalidCipherTextException ex) { throw new RuntimeException(ex); } String[] keys = new String[] { "captchaToken", "captchaValue", "username", "password", "publicKey", "privateKey" }; String[] vals = new String[] { captcha.captchaToken, captchaValue, username, serverPasswordEncoded, Utils.BASE64_URL.encode(publicKey), Utils.BASE64_URL.encode(privateKey) }; HttpURLConnection conn = doRequest("register", null, keys, vals); if (conn.getResponseCode() != 200) { throw new IOException("Server error"); } InputStream in = conn.getInputStream(); JsonNode node = MAPPER.readTree(in); conn.disconnect(); int statusCode = node.get("status").asInt(); if (statusCode == StatusCode.OK) { long userID = node.get("userID").asLong(); long keyTime = node.get("timestamp").asLong(); key.setTime(keyTime); return new CypherUser(username, localPassword, serverPassword, userID, key, keyTime); } else { throw new APIErrorException(statusCode); } }
From source file:com.francetelecom.clara.cloud.paas.it.services.helper.PaasServicesEnvApplicationAccessHelper.java
/** * Check if a string appear in the html page * * @param url/*from ww w . j av a2s.c om*/ * URL to test * @param token * String that must be in html page * @return Cookie that identifies the was or null if the test failed. An * empty string means that no cookie was found in the request, but * the check succeeded. */ private static String checkStringAndReturnCookie(URL url, String token, String httpProxyHost, int httpProxyPort) { InputStream is = null; String cookie = null; try { HttpURLConnection connection; if (httpProxyHost != null) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(httpProxyHost, httpProxyPort)); connection = (HttpURLConnection) url.openConnection(proxy); } else { connection = (HttpURLConnection) url.openConnection(); } connection.setRequestMethod("GET"); is = connection.getInputStream(); // check http status code if (connection.getResponseCode() == 200) { DataInputStream dis = new DataInputStream(new BufferedInputStream(is)); StringWriter writer = new StringWriter(); IOUtils.copy(dis, writer, "UTF-8"); if (writer.toString().contains(token)) { cookie = connection.getHeaderField("Set-Cookie"); if (cookie == null) cookie = ""; } else { logger.info("URL " + url.getFile() + " returned code 200 but does not contain keyword '" + token + "'"); logger.debug("1000 first chars of response body: " + writer.toString().substring(0, 1000)); } } else { logger.error("URL " + url.getFile() + " returned code " + connection.getResponseCode() + " : " + connection.getResponseMessage()); if (System.getProperty("http.proxyHost") != null) { logger.info("Using proxy=" + System.getProperty("http.proxyHost") + ":" + System.getProperty("http.proxyPort")); } } } catch (IOException e) { logger.error("URL test failed: " + url.getFile() + " => " + e.getMessage() + " (" + e.getClass().getName() + ")"); if (System.getProperty("http.proxyHost") != null) { logger.info("Using proxy=" + System.getProperty("http.proxyHost") + ":" + System.getProperty("http.proxyPort")); } } finally { try { if (is != null) { is.close(); } } catch (IOException ioe) { // just going to ignore this one } } return cookie; }
From source file:org.LinuxdistroCommunity.android.client.NetworkUtilities.java
public static String getAuthToken(String server, String code) { String token = null;//w ww . j a va2s .c o m final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_CODE, code)); params.add(new BasicNameValuePair(PARAM_CLIENT_SECRET, CLIENT_SECRET)); InputStream is = null; URL auth_token_url; try { auth_token_url = getRequestURL(server, PATH_OAUTH_ACCESS_TOKEN, params); Log.i(TAG, auth_token_url.toString()); HttpURLConnection conn = (HttpURLConnection) auth_token_url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); int response_code = conn.getResponseCode(); Log.d(TAG, "The response is: " + response_code); is = conn.getInputStream(); // parse token_response as JSON to get the token out String str_response = readStreamToString(is, 500); Log.d(TAG, str_response); JSONObject response = new JSONObject(str_response); token = response.getString("access_token"); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // Makes sure that the InputStream is closed after the app is // finished using it. if (is != null) { try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } Log.i(TAG, token); return token; }
From source file:itdelatrisu.opsu.downloads.BloodcatServer.java
/** * Returns a JSON object from a URL./* ww w . j a v a 2 s.c om*/ * @param url the remote URL * @return the JSON object * @author Roland Illig (http://stackoverflow.com/a/4308662) */ public static JSONObject readJsonFromUrl(URL url) throws IOException { // open connection HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(Download.CONNECTION_TIMEOUT); conn.setReadTimeout(Download.READ_TIMEOUT); conn.setUseCaches(false); try { conn.connect(); } catch (SocketTimeoutException e) { ErrorHandler.error("Connection to server timed out.", e, false); throw e; } if (Thread.interrupted()) return null; // read JSON JSONObject json = null; try (InputStream in = conn.getInputStream()) { BufferedReader rd = new BufferedReader(new InputStreamReader(in)); StringBuilder sb = new StringBuilder(); int c; while ((c = rd.read()) != -1) sb.append((char) c); json = new JSONObject(sb.toString()); } catch (SocketTimeoutException e) { ErrorHandler.error("Connection to server timed out.", e, false); throw e; } catch (JSONException e1) { ErrorHandler.error("Failed to create JSON object.", e1, true); } return json; }