Example usage for java.net URL openConnection

List of usage examples for java.net URL openConnection

Introduction

In this page you can find the example usage for java.net URL openConnection.

Prototype

public URLConnection openConnection() throws java.io.IOException 

Source Link

Document

Returns a java.net.URLConnection URLConnection instance that represents a connection to the remote object referred to by the URL .

Usage

From source file:de.mas.telegramircbot.utils.images.ImgurUploader.java

public static String uploadImageAndGetLink(String clientID, byte[] image) throws IOException {
    URL url;
    url = new URL(Settings.IMGUR_API_URL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    String dataImage = Base64.getEncoder().encodeToString(image);
    String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(dataImage, "UTF-8");

    conn.setDoOutput(true);//from   w  w w.  j a va  2  s.  co  m
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Client-ID " + clientID);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    conn.connect();
    StringBuilder stb = new StringBuilder();
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        stb.append(line).append("\n");
    }
    wr.close();
    rd.close();

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(ImgurResponse.class, new ImgurResponseDeserializer());
    Gson gson = gsonBuilder.create();

    // The JSON data
    try {
        ImgurResponse response = gson.fromJson(stb.toString(), ImgurResponse.class);
        return response.getLink();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return stb.toString();
}

From source file:com.fastbootmobile.encore.api.common.HttpGet.java

/**
 * Downloads the data from the provided URL.
 * @param inUrl The URL to get from//  w w  w . java  2 s .  c  om
 * @param query The query field. '?' + query will be appended automatically, and the query data
 *              MUST be encoded properly.
 * @return A byte array of the data
 */
public static byte[] getBytes(String inUrl, String query, boolean cached)
        throws IOException, RateLimitException {
    final String formattedUrl = inUrl + (query.isEmpty() ? "" : ("?" + query));

    Log.d(TAG, "Formatted URL: " + formattedUrl);

    URL url = new URL(formattedUrl);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestProperty("User-Agent", "OmniMusic/1.0-dev (http://www.omnirom.org)");
    urlConnection.setUseCaches(cached);
    urlConnection.setInstanceFollowRedirects(true);
    int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
    urlConnection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
    try {
        final int status = urlConnection.getResponseCode();
        // MusicBrainz returns 503 Unavailable on rate limit errors. Parse the JSON anyway.
        if (status == HttpURLConnection.HTTP_OK) {
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            int contentLength = urlConnection.getContentLength();
            if (contentLength <= 0) {
                // No length? Let's allocate 100KB.
                contentLength = 100 * 1024;
            }
            ByteArrayBuffer bab = new ByteArrayBuffer(contentLength);
            BufferedInputStream bis = new BufferedInputStream(in);
            int character;

            while ((character = bis.read()) != -1) {
                bab.append(character);
            }
            return bab.toByteArray();
        } else if (status == HttpURLConnection.HTTP_NOT_FOUND) {
            // 404
            return new byte[] {};
        } else if (status == HttpURLConnection.HTTP_FORBIDDEN) {
            return new byte[] {};
        } else if (status == HttpURLConnection.HTTP_UNAVAILABLE) {
            throw new RateLimitException();
        } else if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == 307 /* HTTP/1.1 TEMPORARY REDIRECT */
                || status == HttpURLConnection.HTTP_SEE_OTHER) {
            // We've been redirected, follow the new URL
            final String followUrl = urlConnection.getHeaderField("Location");
            Log.e(TAG, "Redirected to: " + followUrl);
            return getBytes(followUrl, "", cached);
        } else {
            Log.e(TAG, "Error when fetching: " + formattedUrl + " (" + urlConnection.getResponseCode() + ")");
            return new byte[] {};
        }
    } finally {
        urlConnection.disconnect();
    }
}

From source file:cc.vileda.sipgatesync.api.SipgateApi.java

@NonNull
private static HttpURLConnection getConnection(String apiUrl) throws IOException {
    final URL url = new URL(HTTPS_API_SIPGATE_COM_V1 + apiUrl);
    final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestProperty("Content-Type", "application/json");
    urlConnection.setRequestProperty("Accept", "application/json");
    return urlConnection;
}

From source file:com.tmobile.TMobileParsing.java

protected static String getDataFromUrl(String url, String basicAuthToken) throws IOException {
    URL urlObj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) urlObj.openConnection();
    con.setRequestProperty("Authorization", "Basic " + basicAuthToken);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String userInfo = in.readLine(); //Successfull invocation of the web service will see JSON in the HTTP response body
    in.close();/*from   w w w .  j  a  v  a2 s  . co m*/

    return userInfo;
}

From source file:Main.java

public static String getJsonWithPath(String path) {
    StringBuffer sb = new StringBuffer();
    URL url = null;
    HttpURLConnection conn = null;
    BufferedReader br = null;//from   w w w  .  j a v  a  2 s . c o  m

    try {
        url = new URL(path);
        conn = (HttpURLConnection) url.openConnection();
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String temp = "";
            while ((temp = br.readLine()) != null) {
                sb.append(temp);
            }
        } else {
            Log.e(TAG, " NET IS ERROR");
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        close(br);
        conn.disconnect();
    }
    Log.i("TAG", "---" + sb.toString());
    return sb.toString();
}

From source file:Main.java

@SuppressLint("NewApi")
public static void getURL(String path) {
    String fileName = "";
    String dir = "/IndoorNavi/";
    File sdRoot = Environment.getExternalStorageDirectory();
    try {/*from w w w . j  av a 2  s  .c  o m*/
        // Open the URLConnection for reading
        URL u = new URL(path);
        // URL u = new URL("http://www.baidu.com/");
        HttpURLConnection uc = (HttpURLConnection) u.openConnection();

        int code = uc.getResponseCode();
        String response = uc.getResponseMessage();
        //System.out.println("HTTP/1.x " + code + " " + response);
        for (int j = 1;; j++) {
            String key = uc.getHeaderFieldKey(j);
            String header = uc.getHeaderField(j);
            if (!(key == null)) {
                if (key.equals("Content-Name"))
                    fileName = header;
            }
            if (header == null || key == null)
                break;
            //System.out.println(uc.getHeaderFieldKey(j) + ": " + header);
        }
        Log.i("zhr", fileName);
        //System.out.println();

        try (InputStream in = new BufferedInputStream(uc.getInputStream())) {

            // chain the InputStream to a Reader
            Reader r = new InputStreamReader(in);
            int c;
            File mapFile = new File(sdRoot, dir + fileName);
            mapFile.createNewFile();
            FileOutputStream filecon = new FileOutputStream(mapFile);
            while ((c = r.read()) != -1) {
                //System.out.print((char) c);
                filecon.write(c);
                filecon.flush();

            }
            filecon.close();
        }

    } catch (MalformedURLException ex) {
        System.err.println(path + " is not a parseable URL");
    } catch (IOException ex) {
        System.err.println(ex);
    }
}

From source file:edu.xjtu.qxcamerabridge.LiveviewImageExtractor.java

private static InputStream getLiveviewInputStream(String liveviewURL)
        throws MalformedURLException, IOException {
    URL url = new URL(liveviewURL);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setReadTimeout(2000);/*from   ww  w. ja  va2s  . co m*/
    connection.connect();

    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        return connection.getInputStream();
    }
    return null;
}

From source file:resources.XmlToAnime.java

private static InputStream getInput() {
    String username = "shigato";
    String password = "unlimited0";
    String authString = username + ":" + password;
    byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
    String authStringEnc = new String(authEncBytes);
    InputStream in = null;//from w  ww . j a v a  2s  .co  m

    try {
        URL url = new URL(sUrl);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        urlConnection.setRequestProperty("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        urlConnection.setRequestProperty("Accept-Language", "en");
        urlConnection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36");
        in = urlConnection.getInputStream();
        String temp = InputStreamToString.getStringFromInputStream(in);
        temp = Replacer.replaceIllegalCharacters(temp);
        in = new ByteArrayInputStream(temp.getBytes(StandardCharsets.UTF_8));
        System.out.println();

        //            InputStreamReader isr = new InputStreamReader(in);
        //            
        //            int numCharsRead;
        //            char[] charArray = new char[1024];
        //            StringBuilder sb = new StringBuilder();
        //            while ((numCharsRead = isr.read(charArray)) > 0) {
        //                    sb.append(charArray, 0, numCharsRead);
        //            }
        //            String result = sb.toString();
        //            System.out.println(result);

    } catch (IOException e) {

    }
    return in;
}

From source file:de.unigoettingen.sub.commons.util.stream.StreamUtils.java

/************************************************************************************
 * get MimeType as {@link String} from given URL
 * //from w  ww  .j  av a2  s.  c  o  m
 * @param url the url from where to get the MimeType
 * @return MimeType as {@link String}
 * @throws IOException
 ************************************************************************************/
public static String getMimeTypeFromUrl(URL url) throws IOException {

    URLConnection con = url.openConnection();
    return con.getContentType();
}

From source file:dev.meng.wikidata.util.http.HttpUtils.java

public static JSONObject queryForJSONResponse(URL url, String encoding)
        throws ProtocolException, IOException, StringConvertionException {
    JSONObject response = null;// w w w  .j av a2  s .c  om

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.connect();

    if (connection.getResponseCode() == 200) {
        response = new JSONObject(StringUtils.inputStreamToString(connection.getInputStream(), encoding));
    } else {
        throw new IOException("Error in opening: " + url + ", " + connection.getResponseCode() + " "
                + connection.getResponseMessage());
    }

    return response;
}