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:Main.java

public static void post(String actionUrl, String file) {
    try {/*from w w w  .  j  a  v  a 2 s. c o m*/
        URL url = new URL(actionUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);
        con.setRequestMethod("POST");
        con.setRequestProperty("Charset", "UTF-8");
        con.setRequestProperty("Content-Type", "multipart/form-data;boundary=*****");
        DataOutputStream ds = new DataOutputStream(con.getOutputStream());
        FileInputStream fStream = new FileInputStream(file);
        int bufferSize = 1024; // 1MB
        byte[] buffer = new byte[bufferSize];
        int bufferLength = 0;
        int length;
        while ((length = fStream.read(buffer)) != -1) {
            bufferLength = bufferLength + 1;
            ds.write(buffer, 0, length);
        }
        fStream.close();
        ds.flush();
        InputStream is = con.getInputStream();
        int ch;
        StringBuilder b = new StringBuilder();
        while ((ch = is.read()) != -1) {
            b.append((char) ch);
        }
        new String(b.toString().getBytes("ISO-8859-1"), "utf-8");
        ds.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.github.codingtogenomic.CodingToGenomic.java

private static String getContent(final String endpoint)
        throws MalformedURLException, IOException, InterruptedException {

    if (requestCount == 15) { // check every 15
        final long currentTime = System.currentTimeMillis();
        final long diff = currentTime - lastRequestTime;
        //if less than a second then sleep for the remainder of the second
        if (diff < 1000) {
            Thread.sleep(1000 - diff);
        }/*from   w w  w. j  a  v  a2  s .  c o m*/
        //reset
        lastRequestTime = System.currentTimeMillis();
        requestCount = 0;
    }

    final URL url = new URL(SERVER + endpoint);
    URLConnection connection = url.openConnection();
    HttpURLConnection httpConnection = (HttpURLConnection) connection;
    httpConnection.setRequestProperty("Content-Type", "application/json");

    final InputStream response = httpConnection.getInputStream();
    int responseCode = httpConnection.getResponseCode();

    if (responseCode != 200) {
        if (responseCode == 429 && httpConnection.getHeaderField("Retry-After") != null) {
            double sleepFloatingPoint = Double.valueOf(httpConnection.getHeaderField("Retry-After"));
            double sleepMillis = 1000 * sleepFloatingPoint;
            Thread.sleep((long) sleepMillis);
            return getContent(endpoint);
        }
        throw new RuntimeException("Response code was not 200. Detected response was " + responseCode);
    }

    String output;
    Reader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[8192];
        int read;
        while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
            builder.append(buffer, 0, read);
        }
        output = builder.toString();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException logOrIgnore) {
                logOrIgnore.printStackTrace();
            }
        }
    }

    return output;
}

From source file:org.immopoly.android.helper.WebHelper.java

public static JSONObject getHttpData(URL url, boolean signed, Context context) throws JSONException {
    JSONObject obj = null;/*from  w ww.  jav  a 2 s.com*/
    if (Settings.isOnline(context)) {
        HttpURLConnection request;
        try {

            request = (HttpURLConnection) url.openConnection();

            request.addRequestProperty("User-Agent",
                    "immopoly android client " + ImmopolyActivity.getStaticVersionInfo());
            request.addRequestProperty("Accept-Encoding", "gzip");
            if (signed)
                OAuthData.getInstance(context).consumer.sign(request);
            request.setConnectTimeout(SOCKET_TIMEOUT);

            request.connect();
            String encoding = request.getContentEncoding();

            InputStream in;
            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                in = new GZIPInputStream(request.getInputStream());
            } else {
                in = new BufferedInputStream(request.getInputStream());
            }
            String s = readInputStream(in);
            JSONTokener tokener = new JSONTokener(s);
            obj = new JSONObject(tokener);

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (OAuthMessageSignerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (OAuthExpectationFailedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (OAuthCommunicationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return obj;
}

From source file:com.joelapenna.foursquared.appwidget.stats.FoursquareHelper.java

/**
 * Pull the raw text content of the given URL. This call blocks until the
 * operation has completed, and is synchronized because it uses a shared
 * buffer {@link #sBuffer}.//w w w .ja  v a2s.  c  o m
 *
 * @param url The exact URL to request.
 * @return The raw content returned by the server.
 * @throws ApiException If any connection or server error occurs.
 * @author Sections of this code contributed by jTribe (http://jtribe.com.au)
 */
protected static synchronized String getUrlContent(String sUrl, String email, String pword)
        throws ApiException {
    if (sUserAgent == null) {
        throw new ApiException("User-Agent string must be prepared");
    }

    String userPassword = email + ":" + pword;
    String encoding = Base64Coder.encodeString(userPassword);
    try {
        URL url = new URL(sUrl);

        System.setProperty("http.keepAlive", "false");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Authorization", "Basic " + encoding);
        connection.setReadTimeout(REQUEST_TIMEOUT * MILLISECONDS);
        connection.setConnectTimeout(REQUEST_TIMEOUT * MILLISECONDS);
        connection.setRequestProperty("User-Agent", sUserAgent);
        connection.setRequestMethod("GET");

        //Get response code
        int responseCode = connection.getResponseCode();

        if (responseCode != HTTP_STATUS_OK) {
            throw new ApiException("Invalid response from server: " + connection.getResponseMessage());
        }

        // Pull content stream from response
        InputStream inputStream = connection.getInputStream();
        ByteArrayOutputStream content = new ByteArrayOutputStream();

        // Read response into a buffered stream
        int readBytes = 0;
        while ((readBytes = inputStream.read(sBuffer)) != -1) {
            content.write(sBuffer, 0, readBytes);
        }

        // Return result from buffered stream
        return new String(content.toByteArray());
    } catch (IOException e) {
        throw new ApiException("Problem communicating with API", e);
    }
}

From source file:com.mingsoft.weixin.util.UploadDownUtils.java

/**
 * ? //from   ww  w.j a  v a 2s . com
 * 
 * @return
 */
@Deprecated
public static String downMedia(String access_token, String msgType, String media_id, String path) {
    String localFile = null;
    //      SimpleDateFormat df = new SimpleDateFormat("/yyyyMM/");
    try {
        String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + access_token
                + "&media_id=" + media_id;
        // log.error(path);
        // ? ?
        URL urlObj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        String xx = conn.getHeaderField("Content-disposition");
        try {
            log.debug("===? +==?==" + xx);
            if (xx == null) {
                InputStream in = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
                String line = null;
                String result = null;
                while ((line = reader.readLine()) != null) {
                    if (result == null) {
                        result = line;
                    } else {
                        result += line;
                    }
                }
                System.out.println(result);
                JSONObject dataJson = JSONObject.parseObject(result);
                return dataJson.getString("errcode");
            }
        } catch (Exception e) {
        }
        if (conn.getResponseCode() == 200) {
            String Content_disposition = conn.getHeaderField("Content-disposition");
            InputStream inputStream = conn.getInputStream();
            // // ?
            // Long fileSize = conn.getContentLengthLong();
            //  +
            String savePath = path + "/" + msgType;
            // ??
            String fileName = StringUtil.getDateSimpleStr()
                    + Content_disposition.substring(Content_disposition.lastIndexOf(".")).replace("\"", "");
            // 
            File saveDirFile = new File(savePath);
            if (!saveDirFile.exists()) {
                saveDirFile.mkdirs();
            }
            // ??
            if (!saveDirFile.canWrite()) {
                log.error("??");
                throw new Exception();
            }
            // System.out.println("------------------------------------------------");
            // ?
            File file = new File(saveDirFile + "/" + fileName);
            FileOutputStream outStream = new FileOutputStream(file);
            int len = -1;
            byte[] b = new byte[1024];
            while ((len = inputStream.read(b)) != -1) {
                outStream.write(b, 0, len);
            }
            outStream.flush();
            outStream.close();
            inputStream.close();
            // ?
            localFile = fileName;
        }
    } catch (Exception e) {
        log.error("? !", e);
    } finally {

    }
    return localFile;
}

From source file:com.evilisn.DAO.CertMapper.java

public static byte[] httpGetBin(URI uri, boolean bActiveCheckUnknownHost) throws Exception

{

    InputStream is = null;//from w ww  .j  a v a2  s  .  co m

    InputStream is_temp = null;

    try {

        if (uri == null)
            return null;

        URL url = uri.toURL();

        if (bActiveCheckUnknownHost) {

            url.getProtocol();

            String host = url.getHost();

            int port = url.getPort();

            if (port == -1)

                port = url.getDefaultPort();

            InetSocketAddress isa = new InetSocketAddress(host, port);

            if (isa.isUnresolved()) {

                //fix JNLP popup error issue

                throw new UnknownHostException("Host Unknown:" + isa.toString());

            }

        }

        HttpURLConnection uc = (HttpURLConnection) url.openConnection();

        uc.setDoInput(true);

        uc.setAllowUserInteraction(false);

        uc.setInstanceFollowRedirects(true);

        setTimeout(uc);

        String contentEncoding = uc.getContentEncoding();

        int len = uc.getContentLength();

        // is = uc.getInputStream();

        if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("gzip") != -1)

        {

            is_temp = uc.getInputStream();

            is = new GZIPInputStream(is_temp);

        }

        else if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("deflate") != -1)

        {

            is_temp = uc.getInputStream();

            is = new InflaterInputStream(is_temp);

        }

        else

        {

            is = uc.getInputStream();

        }

        if (len != -1) {

            int ch = 0, i = 0;

            byte[] res = new byte[len];

            while ((ch = is.read()) != -1) {

                res[i++] = (byte) (ch & 0xff);

            }

            return res;

        } else {

            ArrayList<byte[]> buffer = new ArrayList<byte[]>();

            int buf_len = 1024;

            byte[] res = new byte[buf_len];

            int ch = 0, i = 0;

            while ((ch = is.read()) != -1) {

                res[i++] = (byte) (ch & 0xff);

                if (i == buf_len) {

                    //rotate

                    buffer.add(res);

                    i = 0;

                    res = new byte[buf_len];

                }

            }

            int total_len = buffer.size() * buf_len + i;

            byte[] buf = new byte[total_len];

            for (int j = 0; j < buffer.size(); j++) {

                System.arraycopy(buffer.get(j), 0, buf, j * buf_len, buf_len);

            }

            if (i > 0) {

                System.arraycopy(res, 0, buf, buffer.size() * buf_len, i);

            }

            return buf;

        }

    } catch (Exception e) {

        e.printStackTrace();

        return null;

    } finally {

        closeInputStream(is_temp);

        closeInputStream(is);

    }

}

From source file:com.qpark.eip.core.spring.security.https.HttpsRequester.java

private static String read(final URL url, final String httpAuthBase64, final HostnameVerifier hostnameVerifier)
        throws IOException {
    StringBuffer sb = new StringBuffer(1024);
    HttpURLConnection connection = null;
    connection = (HttpURLConnection) url.openConnection();
    if (url.getProtocol().equalsIgnoreCase("https")) {
        connection = (HttpsURLConnection) url.openConnection();
        ((HttpsURLConnection) connection).setHostnameVerifier(hostnameVerifier);
    }/* ww  w  .  ja  va 2 s .c o  m*/
    if (httpAuthBase64 != null) {
        connection.setRequestProperty("Authorization", new StringBuffer(httpAuthBase64.length() + 6)
                .append("Basic ").append(httpAuthBase64).toString());
    }
    connection.setRequestProperty("Content-Type", "text/plain; charset=\"utf8\"");
    connection.setRequestMethod("GET");

    int returnCode = connection.getResponseCode();
    InputStream connectionIn = null;
    if (returnCode == 200) {
        connectionIn = connection.getInputStream();
    } else {
        connectionIn = connection.getErrorStream();
    }
    BufferedReader buffer = new BufferedReader(new InputStreamReader(connectionIn));
    String inputLine;
    while ((inputLine = buffer.readLine()) != null) {
        sb.append(inputLine);
    }
    buffer.close();

    return sb.toString();
}

From source file:com.rimbit.android_wallet.ExchangeRatesProvider.java

private static String getURLResult(URL url, final String userAgent) {

    HttpURLConnection connection = null;
    Reader reader = null;/*  w w  w. j ava  2 s . co m*/

    try {
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);

            reader = new InputStreamReader(is, Constants.UTF_8);
            final StringBuilder content = new StringBuilder();

            Io.copy(reader, content);
            return content.toString();

        } else {
            log.warn("http status {} when fetching exchange rates from {}", responseCode, RIMBIT_EXPLORER_URL);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + RIMBIT_EXPLORER_URL, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;

}

From source file:com.memetix.mst.MicrosoftTranslatorAPI.java

/**
 * Gets the OAuth access token./*from   w  w  w.  j  a va2s  .c o m*/
 * @param clientId The Client key.
 * @param clientSecret The Client Secret
 */
public static String getToken(final String clientId, final String clientSecret) throws Exception {
    final String params = "grant_type=client_credentials&scope=http://api.microsofttranslator.com"
            + "&client_id=" + URLEncoder.encode(clientId, ENCODING) + "&client_secret="
            + URLEncoder.encode(clientSecret, ENCODING);

    final URL url = new URL(DatamarketAccessUri);
    final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
    if (referrer != null)
        uc.setRequestProperty("referer", referrer);
    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + ENCODING);
    uc.setRequestProperty("Accept-Charset", ENCODING);
    uc.setRequestMethod("POST");
    uc.setDoOutput(true);

    OutputStreamWriter wr = new OutputStreamWriter(uc.getOutputStream());
    wr.write(params);
    wr.flush();

    try {
        final int responseCode = uc.getResponseCode();
        final String result = inputStreamToString(uc.getInputStream());
        if (responseCode != 200) {
            throw new Exception("Error from Microsoft Translator API: " + result);
        }
        return result;
    } finally {
        if (uc != null) {
            uc.disconnect();
        }
    }
}

From source file:net.daporkchop.porkselfbot.util.HTTPUtils.java

/**
 * Performs a POST request to the specified URL and returns the result.
 * <p />// ww  w .j a  v a  2s .  com
 * The POST data will be encoded in UTF-8 as the specified contentType. The response will be parsed as UTF-8.
 * If the server returns an error but still provides a body, the body will be returned as normal.
 * If the server returns an error without any body, a relevant {@link java.io.IOException} will be thrown.
 *
 * @param url URL to submit the POST request to
 * @param post POST data in the correct format to be submitted
 * @param contentType Content type of the POST data
 * @return Raw text response from the server
 * @throws IOException The request was not successful
 */
public static String performPostRequestWithAuth(final URL url, final String post, final String contentType,
        final String auth) throws IOException {
    Validate.notNull(url);
    Validate.notNull(post);
    Validate.notNull(contentType);
    final HttpURLConnection connection = createUrlConnection(url);
    final byte[] postAsBytes = post.getBytes(Charsets.UTF_8);

    connection.setRequestProperty("Authorization", auth);
    connection.setRequestProperty("Content-Type", contentType + "; charset=utf-8");
    connection.setRequestProperty("Content-Length", "" + postAsBytes.length);
    connection.setDoOutput(true);

    OutputStream outputStream = null;
    try {
        outputStream = connection.getOutputStream();
        IOUtils.write(postAsBytes, outputStream);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }

    InputStream inputStream = null;
    try {
        inputStream = connection.getInputStream();
        final String result = IOUtils.toString(inputStream, Charsets.UTF_8);
        return result;
    } catch (final IOException e) {
        IOUtils.closeQuietly(inputStream);
        inputStream = connection.getErrorStream();

        if (inputStream != null) {
            final String result = IOUtils.toString(inputStream, Charsets.UTF_8);
            return result;
        } else {
            throw e;
        }
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}