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:es.tid.cep.esperanza.Utils.java

public static boolean DoHTTPPost(String urlStr, String content) {
    try {/*from   w  w  w  .  j a  va 2  s  . co m*/
        URL url = new URL(urlStr);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setDoOutput(true);
        urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        OutputStreamWriter printout = new OutputStreamWriter(urlConn.getOutputStream(),
                Charset.forName("UTF-8"));
        printout.write(content);
        printout.flush();
        printout.close();

        int code = urlConn.getResponseCode();
        String message = urlConn.getResponseMessage();
        logger.debug("action http response " + code + " " + message);
        if (code / 100 == 2) {
            InputStream input = urlConn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            for (String line; (line = reader.readLine()) != null;) {
                logger.debug("action response body: " + line);
            }
            input.close();
            return true;

        } else {
            logger.error("action response is not OK: " + code + " " + message);
            InputStream error = urlConn.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(error));
            for (String line; (line = reader.readLine()) != null;) {
                logger.error("action error response body: " + line);
            }
            error.close();
            return false;
        }
    } catch (MalformedURLException me) {
        logger.error("exception MalformedURLException: " + me.getMessage());
        return false;
    } catch (IOException ioe) {
        logger.error("exception IOException: " + ioe.getMessage());
        return false;
    }
}

From source file:website.openeng.anki.web.HttpFetcher.java

public static String downloadFileToSdCardMethod(String UrlToFile, Context context, String prefix,
        String method) {// w ww. j av a2s. c  o m
    try {
        URL url = new URL(UrlToFile);

        String extension = UrlToFile.substring(UrlToFile.length() - 4);

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod(method);
        urlConnection.setRequestProperty("Referer", "website.openeng.anki");
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
        urlConnection.setRequestProperty("Accept", "*/*");
        urlConnection.setConnectTimeout(10000);
        urlConnection.setReadTimeout(60000);
        urlConnection.connect();

        File file = File.createTempFile(prefix, extension, context.getCacheDir());

        FileOutputStream fileOutput = new FileOutputStream(file);
        InputStream inputStream = urlConnection.getInputStream();

        byte[] buffer = new byte[1024];
        int bufferLength = 0;

        while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
        }
        fileOutput.close();

        return file.getAbsolutePath();

    } catch (Exception e) {
        return "FAILED " + e.getMessage();
    }
}

From source file:oneDrive.OneDriveAPI.java

public static String connectWithREST(String url, String method) throws IOException, ProtocolException {
    String newURL = "";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    // Connect with a REST Method: GET, DELETE, PUT
    con.setRequestMethod(method);//from  w ww .j  ava 2 s  .com
    //add request header
    con.setReadTimeout(20000);
    con.setConnectTimeout(20000);
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    if (method.equals(DELETE) || method.equals(PUT) || getSize)
        con.addRequestProperty("Authorization", "Bearer " + ACCESS_TOKEN);

    int responseCode = con.getResponseCode();
    // Read response
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    newURL = response.toString();

    return newURL;
}

From source file:Main.java

public static String stringFromHttpPost(String urlStr, String body) {
    HttpURLConnection conn;
    try {/*from  w w  w  . j  a  v a  2 s . c  om*/
        URL e = new URL(urlStr);
        conn = (HttpURLConnection) e.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestMethod("POST");
        OutputStream os1 = conn.getOutputStream();
        DataOutputStream out1 = new DataOutputStream(os1);
        out1.write(body.getBytes("UTF-8"));
        out1.flush();
        conn.connect();
        String line;
        BufferedReader reader;
        StringBuffer sb = new StringBuffer();
        if ("gzip".equals(conn.getHeaderField("Content-Encoding"))) {
            reader = new BufferedReader(
                    new InputStreamReader(new GZIPInputStream(conn.getInputStream()), "UTF-8"));
        } else {
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        }
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
        logError(e.getMessage());
    }
    return null;
}

From source file:com.appdynamics.common.RESTClient.java

public static void sendPost(String urlString, String input, String apiKey) {
    try {//w w w .j  av a  2  s .  com
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");

        conn.setRequestProperty("Authorization",
                "Basic " + new String(Base64.encodeBase64((apiKey).getBytes())));

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String output;
        logger.info("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            logger.info(output);
        }

        conn.disconnect();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

}

From source file:com.appsimobile.appsii.module.weather.WeatherLoadingService.java

private static boolean downloadFile(Context context, ImageDownloadHelper.PhotoInfo photoInfo, String woeid,
        int idx) {

    WeatherUtils weatherUtils = AppInjector.provideWeatherUtils();

    File cacheDir = weatherUtils.getWeatherPhotoCacheDir(context);
    String fileName = weatherUtils.createPhotoFileName(woeid, idx);
    File photoImage = new File(cacheDir, fileName);
    try {/*from  w  w w.j  av a 2  s.  c  o  m*/
        URL url = new URL(photoInfo.url);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(30000);
        InputStream in = new BufferedInputStream(connection.getInputStream());
        try {
            OutputStream out = new BufferedOutputStream(new FileOutputStream(photoImage));

            int totalRead = 0;
            try {
                byte[] bytes = new byte[64 * 1024];
                int read;
                while ((read = in.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                    totalRead += read;
                }
                out.flush();
            } finally {
                out.close();
            }
            if (BuildConfig.DEBUG) {
                Log.d("WeatherLoadingService", "received " + totalRead + " bytes for: " + photoInfo.url);
            }
        } finally {
            in.close();
        }
        return true;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:org.voota.api.VootaApi.java

/**
 * Loads image data by url and returns byte array filled by this data. If
 * method fails to load image, it will return null.
 *
 * @param  urlImage          url represents image to load
 * @return                   byte array filled by image data or null if image
 *                           loading fails
 *//*from  w  w w.jav a2 s.co  m*/
static public byte[] getUrlImageBytes(URL urlImage) {
    byte[] bytesImage = null;
    try {
        HttpURLConnection conn = (HttpURLConnection) urlImage.openConnection();
        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();

        int bytesAvavilable = conn.getContentLength();
        bytesImage = new byte[bytesAvavilable];
        int nReaded = 0, nSum = 0;

        while (bytesAvavilable > nSum) {
            nReaded = is.read(bytesImage, nSum, bytesAvavilable - nSum);
            nSum += nReaded;
        }
    } catch (IOException e) {
    }

    return bytesImage;
}

From source file:org.voota.api.VootaApi.java

/**
 * Loads image data by url and returns byte array filled by this data. If
 * method fails to load image, it will return null. This method takes url as
 * String object and converts file name to used character set, because it
 * may contain Spanish symbols. /*from ww w .j  ava  2s  . co m*/
 *
 * @param  urlImage          url in String object represents image to load
 * @return                   byte array filled by image data or null if image
 *                           loading fails
 */
static public byte[] getUrlImageBytes(String strUrlImage) {
    byte[] bytesImage = null;
    try {
        URL urlImage = new URL(getEncodedImageUrl(strUrlImage));
        HttpURLConnection conn = (HttpURLConnection) urlImage.openConnection();
        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();

        int bytesAvavilable = conn.getContentLength();
        bytesImage = new byte[bytesAvavilable];
        int nReaded = 0, nSum = 0;

        while (bytesAvavilable > nSum) {
            nReaded = is.read(bytesImage, nSum, bytesAvavilable - nSum);
            nSum += nReaded;
        }
    } catch (IOException e) {
    }

    return bytesImage;
}

From source file:Main.java

public static String executePost(String url, String parameters) throws IOException {

    URL request = new URL(url);
    HttpURLConnection connection = (HttpURLConnection) request.openConnection();
    connection.setDoOutput(true);/*w  w w. j av  a 2s .c o m*/
    connection.setDoInput(true);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("User-Agent", "StripeConnectAndroid");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("charset", "utf-8");
    connection.setRequestProperty("Content-Length", "" + Integer.toString(parameters.getBytes().length));
    connection.setUseCaches(false);

    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.writeBytes(parameters);
    wr.flush();
    wr.close();

    String response = streamToString(connection.getInputStream());
    connection.disconnect();
    return response;

}

From source file:Main.java

/**
 * Issue a POST request to the server.//ww  w .j av  a2 s  .c o m
 *
 * @param endpoint
 *            POST address.
 * @param params
 *            request parameters.
 *
 * @throws IOException
 *             propagated from POST.
 */
public static String post_t(String endpoint, Map<String, Object> params, String contentType)
        throws IOException {
    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, Object>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, Object> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", contentType);
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response
        int status = conn.getResponseCode();
        if (status != 200) {
            throw new IOException("Post failed with error code " + status);
        }

        // Get Response
        InputStream is = conn.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\n');
        }
        rd.close();
        return response.toString();

    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}