List of usage examples for java.net URL openConnection
public URLConnection openConnection() throws java.io.IOException
From source file:Main.java
/** * Download the avatar image from the server. * * @param avatarUrl the URL pointing to the avatar image * @return a byte array with the raw JPEG avatar image *//*from w w w . j a v a 2 s .com*/ public static byte[] downloadAvatar(final String avatarUrl) { // If there is no avatar, we're done if (TextUtils.isEmpty(avatarUrl)) { return null; } try { Log.i(TAG, "Downloading avatar: " + avatarUrl); // Request the avatar image from the server, and create a bitmap // object from the stream we get back. URL url = new URL(avatarUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); try { final BitmapFactory.Options options = new BitmapFactory.Options(); final Bitmap avatar = BitmapFactory.decodeStream(connection.getInputStream(), null, options); // Take the image we received from the server, whatever format it // happens to be in, and convert it to a JPEG image. Note: we're // not resizing the avatar - we assume that the image we get from // the server is a reasonable size... Log.i(TAG, "Converting avatar to JPEG"); ByteArrayOutputStream convertStream = new ByteArrayOutputStream( avatar.getWidth() * avatar.getHeight() * 4); avatar.compress(Bitmap.CompressFormat.JPEG, 95, convertStream); convertStream.flush(); convertStream.close(); // On pre-Honeycomb systems, it's important to call recycle on bitmaps avatar.recycle(); return convertStream.toByteArray(); } finally { connection.disconnect(); } } catch (MalformedURLException muex) { // A bad URL - nothing we can really do about it here... Log.e(TAG, "Malformed avatar URL: " + avatarUrl); } catch (IOException ioex) { // If we're unable to download the avatar, it's a bummer but not the // end of the world. We'll try to get it next time we sync. Log.e(TAG, "Failed to download user avatar: " + avatarUrl); } return null; }
From source file:edu.sdsc.solr.lemmatization.LemmatizationWriter.java
static void downloadDictionary(URL definitionUrl, File target) throws IOException { try (InputStream is = new GZIPInputStream(definitionUrl.openConnection().getInputStream())) { FileUtils.copyInputStreamToFile(is, target); }//w w w . ja va2s. co m }
From source file:net.meltdowntech.steamstats.SteamGame.java
public static List<SteamGame> fetchGames(SteamUser user, boolean all) { List<SteamGame> games = new ArrayList<>(); Util.printDebug("Fetching games"); //Create query url String url = Steam.URL + Steam.GAME_OWNED + "?key=" + Steam.KEY + "&include_played_free_games&steamid=" + user.getCommunityId();/*from www . j a v a2s.c o m*/ try { //Attempt connection and parse URL steam = new URL(url); URLConnection steamConn = steam.openConnection(); Reader steamReader = new InputStreamReader(steamConn.getInputStream()); JSONTokener steamTokener = new JSONTokener(steamReader); JSONObject data = (JSONObject) steamTokener.nextValue(); JSONObject response = data.getJSONObject("response"); JSONArray apps = response.getJSONArray("games"); Util.printInfo(String.format("%d game%s allotted", apps.length(), apps.length() == 1 ? "" : "s")); //Parse each game for (int y = 0; y < apps.length(); y++) { JSONObject app = apps.getJSONObject(y); SteamGame game = all ? fetchGame(app.getInt("appid")) : new SteamGame(); //Parse each field Iterator keys = app.keys(); while (keys.hasNext()) { String key = (String) keys.next(); game.values.put(key, app.get(key)); } games.add(game); } } catch (MalformedURLException ex) { Util.printError("Invalid URL"); } catch (IOException | JSONException ex) { Util.printError("Invalid data"); } catch (Exception ex) { Util.printError("Generic error"); } Util.printDebug("Done fetching games"); return games; }
From source file:com.linkedin.pinot.tools.admin.command.AbstractBaseAdminCommand.java
public static String sendPostRequest(String urlString, String payload) throws UnsupportedEncodingException, IOException, JSONException { final URL url = new URL(urlString); final URLConnection conn = url.openConnection(); conn.setDoOutput(true);//from w w w . ja v a2 s.c o m 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); } return sb.toString(); }
From source file:Main.java
public static String getToken(String email, String password) throws IOException { // Create the post data // Requires a field with the email and the password StringBuilder builder = new StringBuilder(); builder.append("Email=").append(email); builder.append("&Passwd=").append(password); builder.append("&accountType=GOOGLE"); builder.append("&source=markson.visuals.sitapp"); builder.append("&service=ac2dm"); // Setup the Http Post byte[] data = builder.toString().getBytes(); URL url = new URL("https://www.google.com/accounts/ClientLogin"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setUseCaches(false);/* w w w . ja v a 2 s . com*/ con.setDoOutput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("Content-Length", Integer.toString(data.length)); // Issue the HTTP POST request OutputStream output = con.getOutputStream(); output.write(data); output.close(); // Read the response BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); String line = null; String auth_key = null; while ((line = reader.readLine()) != null) { if (line.startsWith("Auth=")) { auth_key = line.substring(5); } } // Finally get the authentication token // To something useful with it return auth_key; }
From source file:Main.java
public static byte[] downloadImage(final URL url) { InputStream in = null;// w w w.java 2 s.c om int responseCode = -1; try { final HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoInput(true); con.connect(); responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { in = con.getInputStream(); return getByteFromInputStream(in); } } catch (final IOException e) { Log.e(LOG_TAG, "Failed to download image from: " + url.toString(), e); } return null; }
From source file:Main.java
public static String uploadFile(File file, String RequestURL) { String BOUNDARY = UUID.randomUUID().toString(); String PREFIX = "--", LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; try {//from w w w . j a v a2 s . com URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Charset", CHARSET); conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); if (file != null) { OutputStream outputSteam = conn.getOutputStream(); DataOutputStream dos = new DataOutputStream(outputSteam); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); sb.append("Content-Disposition: form-data; name=\"img\"; filename=\"" + file.getName() + "\"" + LINE_END); sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); InputStream is = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1) { dos.write(bytes, 0, len); } is.close(); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes(); dos.write(end_data); dos.flush(); int res = conn.getResponseCode(); Log.e(TAG, "response code:" + res); if (res == 200) { return SUCCESS; } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return FAILURE; }
From source file:Main.java
public static String executeHttpsPost(String url, String data, InputStream key) { HttpsURLConnection localHttpsURLConnection = null; try {/* w w w .ja v a2 s . c o m*/ URL localURL = new URL(url); localHttpsURLConnection = (HttpsURLConnection) localURL.openConnection(); localHttpsURLConnection.setRequestMethod("POST"); localHttpsURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); localHttpsURLConnection.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length)); localHttpsURLConnection.setRequestProperty("Content-Language", "en-US"); localHttpsURLConnection.setUseCaches(false); localHttpsURLConnection.setDoInput(true); localHttpsURLConnection.setDoOutput(true); localHttpsURLConnection.connect(); Certificate[] arrayOfCertificate = localHttpsURLConnection.getServerCertificates(); byte[] arrayOfByte1 = new byte[294]; DataInputStream localDataInputStream = new DataInputStream(key); localDataInputStream.readFully(arrayOfByte1); localDataInputStream.close(); Certificate localCertificate = arrayOfCertificate[0]; PublicKey localPublicKey = localCertificate.getPublicKey(); byte[] arrayOfByte2 = localPublicKey.getEncoded(); for (int i = 0; i < arrayOfByte2.length; i++) { if (arrayOfByte2[i] != arrayOfByte1[i]) throw new RuntimeException("Public key mismatch"); } DataOutputStream localDataOutputStream = new DataOutputStream( localHttpsURLConnection.getOutputStream()); localDataOutputStream.writeBytes(data); localDataOutputStream.flush(); localDataOutputStream.close(); InputStream localInputStream = localHttpsURLConnection.getInputStream(); BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(localInputStream)); StringBuffer localStringBuffer = new StringBuffer(); String str1; while ((str1 = localBufferedReader.readLine()) != null) { localStringBuffer.append(str1); localStringBuffer.append('\r'); } localBufferedReader.close(); return localStringBuffer.toString(); } catch (Exception localException) { byte[] arrayOfByte1; localException.printStackTrace(); return null; } finally { if (localHttpsURLConnection != null) localHttpsURLConnection.disconnect(); } }
From source file:com.cnaude.mutemanager.UUIDFetcher.java
private static HttpURLConnection createConnection() throws Exception { URL url = new URL(PROFILE_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setUseCaches(false);//from w ww . ja v a 2 s. c o m connection.setDoInput(true); connection.setDoOutput(true); return connection; }
From source file:Main.java
public static String customrequest(String url, HashMap<String, String> params, String method) { try {/* w w w . j a v a2s .co m*/ URL postUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setConnectTimeout(5 * 1000); conn.setRequestMethod(method); conn.setUseCaches(false); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)"); conn.connect(); OutputStream out = conn.getOutputStream(); StringBuilder sb = new StringBuilder(); if (null != params) { int i = params.size(); for (Map.Entry<String, String> entry : params.entrySet()) { if (i == 1) { sb.append(entry.getKey() + "=" + entry.getValue()); } else { sb.append(entry.getKey() + "=" + entry.getValue() + "&"); } i--; } } String content = sb.toString(); out.write(content.getBytes("UTF-8")); out.flush(); out.close(); InputStream inStream = conn.getInputStream(); String result = inputStream2String(inStream); conn.disconnect(); return result; } catch (Exception e) { // TODO: handle exception } return null; }