Example usage for java.net HttpURLConnection getInputStream

List of usage examples for java.net HttpURLConnection getInputStream

Introduction

In this page you can find the example usage for java.net HttpURLConnection getInputStream.

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

From source file:net.servicestack.client.Utils.java

public static String readToEnd(HttpURLConnection response) {
    try {//from  w  w w.j a v  a2  s  .  co  m
        return readToEnd(response.getInputStream(), "UTF-8");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.cyphermessenger.client.SyncRequest.java

public static Captcha requestCaptcha() throws IOException, APIErrorException {
    HttpURLConnection conn = doRequest("captcha");
    if (conn.getResponseCode() != 200) {
        throw new IOException("Server error");
    }/*from w w w.j  ava  2  s .c o  m*/
    InputStream in = conn.getInputStream();
    JsonNode node = MAPPER.readTree(in);
    conn.disconnect();
    int statusCode = node.get("status").asInt();
    String captchaTokenString = node.get("captchaToken").asText();
    String captchaHashString = node.get("captchaHash").asText();
    String captchaImageString = node.get("captchaBytes").asText();

    byte[] captchaHash = Utils.BASE64_URL.decode(captchaHashString);
    byte[] captchaImage = Utils.BASE64_URL.decode(captchaImageString);
    if (statusCode == StatusCode.OK) {
        return new Captcha(captchaTokenString, captchaHash, captchaImage);
    } else {
        throw new APIErrorException(statusCode);
    }
}

From source file:Main.java

static String validGet(URL url) throws IOException {
    String html = "";
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
    // TODO ensure HttpsURLConnection.setDefaultSSLSocketFactory isn't
    // required to be reset like hostnames are
    HttpURLConnection conn = null;
    try {//  w w  w. j  a v  a2s  .c o  m
        conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setRequestMethod("GET");
        setBasicAuthentication(conn, url);
        int status = conn.getResponseCode();
        if (status != 200) {
            Logd(TAG, "Failed to get from server, returned code: " + status);
            throw new IOException("Get failed with error code " + status);
        } else {
            InputStreamReader in = new InputStreamReader(conn.getInputStream());
            BufferedReader br = new BufferedReader(in);
            String decodedString;
            while ((decodedString = br.readLine()) != null) {
                html += decodedString;
            }
            in.close();
        }
    } catch (IOException e) {
        Logd(TAG, "Failed to get from server: " + e.getMessage());
    }
    if (conn != null) {
        conn.disconnect();
    }
    return html;
}

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.  j  a  v  a  2 s .  c om*/
    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:net.amigocraft.mpt.util.MiscUtil.java

public static JSONObject getRemoteIndex(String path) throws MPTException {
    try {/* w w w. j av a2s  .c o m*/
        URL url = new URL(path + (!path.endsWith("/") ? "/" : "") + "mpt.json"); // get URL object for data file
        URLConnection conn = url.openConnection();
        if (conn instanceof HttpURLConnection) {
            HttpURLConnection http = (HttpURLConnection) conn; // cast the connection
            int response = http.getResponseCode(); // get the response
            if (response >= 200 && response <= 299) { // verify the remote isn't upset at us
                InputStream is = http.getInputStream(); // open a stream to the URL
                BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // get a reader
                JSONParser parser = new JSONParser(); // get a new parser
                String line;
                StringBuilder content = new StringBuilder();
                while ((line = reader.readLine()) != null)
                    content.append(line);
                JSONObject json = (JSONObject) parser.parse(content.toString()); // parse JSON object
                // vefify remote config is valid
                if (json.containsKey("packages") && json.get("packages") instanceof JSONObject) {
                    return json;
                } else
                    throw new MPTException(
                            ERROR_COLOR + "Index for repository at " + path + "is missing required elements!");
            } else {
                String error = ERROR_COLOR + "Remote returned bad response code! (" + response + ")";
                if (!http.getResponseMessage().isEmpty())
                    error += " The remote says: " + ChatColor.GRAY + ChatColor.ITALIC
                            + http.getResponseMessage();
                throw new MPTException(error);
            }
        } else
            throw new MPTException(ERROR_COLOR + "Bad protocol for URL!");
    } catch (MalformedURLException ex) {
        throw new MPTException(ERROR_COLOR + "Cannot parse URL!");
    } catch (IOException ex) {
        throw new MPTException(ERROR_COLOR + "Cannot open connection to URL!");
    } catch (ParseException ex) {
        throw new MPTException(ERROR_COLOR + "Repository index is not valid JSON!");
    }
}

From source file:net.servicestack.client.Utils.java

public static byte[] readBytesToEnd(HttpURLConnection response) {
    try {/*www  .  ja v  a2s  .co m*/
        return readBytesToEnd(response.getInputStream());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.keepsafe.switchboard.SwitchBoard.java

/**
 * Returns a String containing the server response from a GET request
 * @param address Valid http addess.// w ww.  ja  va2s.c  o m
 * @param params String of params. Multiple params seperated with &. No leading ? in string
 * @return Returns String from server or null when failed.
 */
private static String readFromUrlGET(String address, String params) {
    if (address == null || params == null)
        return null;

    String completeUrl = address + "?" + params;
    if (DEBUG)
        Log.d(TAG, "readFromUrl(): " + completeUrl);

    try {
        URL url = new URL(completeUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setUseCaches(false);
        connection.setDoOutput(true);

        // get response
        InputStream is = connection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(is);
        BufferedReader bufferReader = new BufferedReader(inputStreamReader, 8192);
        String line = "";
        StringBuffer resultContent = new StringBuffer();
        while ((line = bufferReader.readLine()) != null) {
            if (DEBUG)
                Log.d(TAG, line);
            resultContent.append(line);
        }
        bufferReader.close();

        if (DEBUG)
            Log.d(TAG, "readFromUrl() result: " + resultContent.toString());

        return resultContent.toString();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:net.andylizi.colormotd.utils.AttributionUtil.java

private static String sendGet(String url, String param, String charset) {
    StringBuilder result = new StringBuilder(1024);
    BufferedReader in = null;/*from ww w .j a v  a  2 s. c  o m*/
    try {
        String urlNameString = url + "?" + param;
        URL realUrl = new URL(urlNameString);
        HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
        conn.setRequestProperty("User-Agent", "ColorMOTD/" + UUID.randomUUID());
        conn.setRequestProperty("Accept-Charset", charset);
        conn.setUseCaches(true);
        conn.setConnectTimeout(2000);
        conn.setReadTimeout(3000);
        conn.connect();
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.forName(charset)), 1024);
        String line;
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
        conn.disconnect();
    } catch (Exception e) {
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e2) {
        }
    }
    return result.toString();
}

From source file:com.uk_postcodes.api.Postcode.java

/**
 * Get the postcode closest to the location.
 * @param location The device's location
 * @return the closest postcode// w w w .  ja va  2 s  .c  o  m
 * @throws Exception
 */
public static String forLocation(Location location) throws Exception {
    String address = String.format(CALL, location.getLatitude(), location.getLongitude());

    Log.d("Postcode", "Calling: " + address);

    URL callUrl = new URL(address);
    HttpURLConnection callConnection = (HttpURLConnection) callUrl.openConnection();
    // The ten-second rule:
    // If there's no data in 10s (or TIMEOUT), assume the worst.
    callConnection.setReadTimeout(10000);
    // Set the request method to GET.
    callConnection.setRequestMethod("GET");
    int code = callConnection.getResponseCode();
    if (code != HttpURLConnection.HTTP_OK) {
        throw new Exception("A non-200 code was returned: " + code);
    }

    String responseStr;
    responseStr = IOUtils.toString(callConnection.getInputStream());
    callConnection.disconnect();

    JsonParser jp = new JsonParser();
    JsonElement response = jp.parse(responseStr);
    return response.getAsJsonObject().get("postcode").getAsString();
}

From source file:Main.java

public static ArrayList autocomplete(String input) {
    ArrayList resultList = null;/*from   w w w.  j a v  a2 s . c o m*/

    HttpURLConnection conn = null;
    StringBuilder jsonResults = new StringBuilder();
    try {
        StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
        sb.append("?key=" + API_KEY);
        //sb.append("&components=country:gr");
        sb.append("&sensor=false");
        sb.append("&input=" + URLEncoder.encode(input, "utf8"));

        URL url = new URL(sb.toString());
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Load the results into a StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            jsonResults.append(buff, 0, read);
        }
    } catch (MalformedURLException e) {
        //Log.e(LOG_TAG, "Error processing Places API URL", e);
        return resultList;
    } catch (IOException e) {
        // Log.e(LOG_TAG, "Error connecting to Places API", e);
        return resultList;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    try {
        // Create a JSON object hierarchy from the results
        JSONObject jsonObj = new JSONObject(jsonResults.toString());
        JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");

        // Extract the Place descriptions from the results
        resultList = new ArrayList(predsJsonArray.length());
        for (int i = 0; i < predsJsonArray.length(); i++) {
            System.out.println(predsJsonArray.getJSONObject(i).getString("description"));
            System.out.println("============================================================");
            resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
        }
    } catch (JSONException e) {
        //Log.e(LOG_TAG, "Cannot process JSON results", e);
    }

    return resultList;
}