Example usage for java.net URLConnection getInputStream

List of usage examples for java.net URLConnection getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

From source file:com.jiubang.core.util.HttpUtils.java

/**
 * Send an HTTP(s) request with POST parameters.
 * //  w w w  .  j  a v  a 2s .  c o m
 * @param parameters
 * @param url
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
static void doPost(Map<?, ?> parameters, URL url)
        throws UnsupportedEncodingException, IOException, KeyManagementException, NoSuchAlgorithmException {

    URLConnection cnx = getConnection(url);

    // Construct data
    StringBuilder dataBfr = new StringBuilder();
    Iterator<?> iKeys = parameters.keySet().iterator();
    while (iKeys.hasNext()) {
        if (dataBfr.length() != 0) {
            dataBfr.append('&');
        }
        String key = (String) iKeys.next();
        dataBfr.append(URLEncoder.encode(key, "UTF-8")).append('=')
                .append(URLEncoder.encode((String) parameters.get(key), "UTF-8"));
    }
    // POST data
    cnx.setDoOutput(true);

    OutputStreamWriter wr = new OutputStreamWriter(cnx.getOutputStream());
    Loger.d(LOG_TAG, "Posting crash report data");
    wr.write(dataBfr.toString());
    wr.flush();
    wr.close();

    Loger.d(LOG_TAG, "Reading response");
    BufferedReader rd = new BufferedReader(new InputStreamReader(cnx.getInputStream()));

    String line;
    while ((line = rd.readLine()) != null) {
        Loger.d(LOG_TAG, line);
    }
    rd.close();
}

From source file:com.baidu.api.client.core.DownloadUtil.java

/**
 * Download the file pointed by the url and return the content as byte array.
 *
 * @param strUrl         The Url to be downloaded.
 * @param connectTimeout Connect timeout in milliseconds.
 * @param readTimeout    Read timeout in milliseconds.
 * @param maxFileSize    Max file size in BYTE.
 * @return The file content as byte array.
 *///  ww w  . j  av a2s .  com
public static byte[] downloadFile(String strUrl, int connectTimeout, int readTimeout, int maxFileSize) {
    InputStream in = null;
    try {
        URL url = new URL(strUrl); // URL?
        URLConnection ucon = url.openConnection();
        ucon.setConnectTimeout(connectTimeout);
        ucon.setReadTimeout(readTimeout);
        ucon.connect();
        if (ucon.getContentLength() > maxFileSize) {
            String msg = "File " + strUrl + " size [" + ucon.getContentLength()
                    + "] too large, download stoped.";
            throw new ClientInternalException(msg);
        }
        if (ucon instanceof HttpURLConnection) {
            HttpURLConnection httpCon = (HttpURLConnection) ucon;
            if (httpCon.getResponseCode() > 399) {
                String msg = "Failed to download file " + strUrl + " server response "
                        + httpCon.getResponseMessage();
                throw new ClientInternalException(msg);
            }
        }
        in = ucon.getInputStream(); // ?
        byte[] byteBuf = new byte[BUFFER_SIZE];
        byte[] ret = null;
        int count, total = 0;
        // ??
        while ((count = in.read(byteBuf, total, BUFFER_SIZE - total)) > 0) {
            total += count;
            if (total + 124 >= BUFFER_SIZE)
                break;
        }
        if (total < BUFFER_SIZE - 124) {
            ret = ArrayUtils.subarray(byteBuf, 0, total);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream(MATERIAL_SIZE);
            count = total;
            total = 0;
            do {
                bos.write(byteBuf, 0, count);
                total += count;
                if (total > maxFileSize) {
                    String msg = "File " + strUrl + " size exceed [" + maxFileSize + "] download stoped.";
                    throw new ClientInternalException(msg);
                }
            } while ((count = in.read(byteBuf)) > 0);
            ret = bos.toByteArray();
        }
        if (ret.length < MIN_SIZE) {
            String msg = "File " + strUrl + " size [" + maxFileSize + "] too small.";
            throw new ClientInternalException(msg);
        }
        return ret;
    } catch (IOException e) {
        String msg = "Failed to download file " + strUrl + " msg=" + e.getMessage();
        throw new ClientInternalException(msg);
    } finally {
        try {
            if (in != null)
                in.close();
        } catch (IOException e) {
            // ?
            System.out.println("Exception while close url - " + e.getMessage());
        }
    }
}

From source file:BihuHttpUtil.java

public static String doHttpPost(String xmlInfo, String URL) {
    System.out.println("??:" + xmlInfo);
    byte[] xmlData = xmlInfo.getBytes();
    InputStream instr = null;//ww w  . ja va 2s . c o  m
    java.io.ByteArrayOutputStream out = null;
    try {
        URL url = new URL(URL);
        URLConnection urlCon = url.openConnection();
        urlCon.setDoOutput(true);
        urlCon.setDoInput(true);
        urlCon.setUseCaches(false);
        urlCon.setRequestProperty("Content-Type", "text/xml");
        urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length));
        System.out.println(String.valueOf(xmlData.length));
        DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
        printout.write(xmlData);
        printout.flush();
        printout.close();
        instr = urlCon.getInputStream();
        byte[] bis = IOUtils.toByteArray(instr);
        String ResponseString = new String(bis, "UTF-8");
        if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
            System.out.println("");
        }
        System.out.println("?:" + ResponseString);
        return ResponseString;

    } catch (Exception e) {
        e.printStackTrace();
        return "0";
    } finally {
        try {
            out.close();
            instr.close();
        } catch (Exception ex) {
            return "0";
        }
    }
}

From source file:mas.MAS.java

/**
 * @param args the command line arguments
 *///from w  w  w .  jav  a  2 s  .  c o m
public static String getData_old(String url_org, int start) {
    try {
        String complete_url = url_org + "&$skip=" + start;
        //            String url_str = generateURL(url_org, prop);
        URL url = new URL(complete_url);
        URLConnection yc = url.openConnection();
        yc.setConnectTimeout(25 * 1000);
        yc.setReadTimeout(25 * 1000);
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;
        StringBuffer result = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            //                System.out.println(inputLine);
            result.append(inputLine);
        }
        in.close();
        return result.toString();
    } catch (MalformedURLException ex) {
        Logger.getLogger(MAS.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(MAS.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:com.sun.faces.generate.RenderKitSpecificationGenerator.java

public static void appendResourceToStringBuffer(String resourceName, StringBuffer sb) throws Exception {
    InputStreamReader isr = null;
    URL url = null;//  ww w  . j av  a  2s .  com
    URLConnection conn = null;
    char[] chars = new char[1024];
    int len = 0;

    url = getCurrentLoader(sb).getResource(resourceName);
    conn = url.openConnection();
    conn.setUseCaches(false);
    isr = new InputStreamReader(conn.getInputStream());
    while (-1 != (len = isr.read(chars, 0, 1024))) {
        sb.append(chars, 0, len);
    }
    isr.close();
}

From source file:com.moviejukebox.plugin.OpenSubtitlesPlugin.java

private static String sendRPC(String xml) throws IOException {

    StringBuilder str = new StringBuilder();
    String strona = OS_DB_SERVER;
    String logowanie = xml;//from w  w w .  j av  a 2s .  co  m
    URL url = new URL(strona);
    URLConnection connection = url.openConnection();
    connection.setRequestProperty("Connection", "Close");

    // connection.setRequestProperty("Accept","text/html");
    connection.setRequestProperty("Content-Type", "text/xml");
    connection.setDoOutput(Boolean.TRUE);

    connection.getOutputStream().write(logowanie.getBytes("UTF-8"));

    try (Scanner in = new Scanner(connection.getInputStream())) {
        while (in.hasNextLine()) {
            str.append(in.nextLine());
        }
    }

    ((HttpURLConnection) connection).disconnect();

    return str.toString();
}

From source file:com.beyondb.geocoding.BaiduAPI.java

public static Map<String, String> testPost(String x, String y) throws IOException {
    URL url = new URL("http://api.map.baidu.com/geocoder?" + ak + "="
            + "&callback=renderReverse&location=" + x + "," + y + "&output=json");
    URLConnection connection = url.openConnection();
    /**// w  w  w . j a  va  2  s .  c  om
     * ??URLConnection?Web
     * URLConnection???Web???
     */
    connection.setDoOutput(true);
    OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
    //        remember to clean up
    out.flush();
    out.close();
    //        ?????
    String res;
    InputStream l_urlStream;
    l_urlStream = connection.getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(l_urlStream, "UTF-8"));
    StringBuilder sb = new StringBuilder("");
    while ((res = in.readLine()) != null) {
        sb.append(res.trim());
    }
    String str = sb.toString();
    System.out.println(str);
    Map<String, String> map = null;
    if (StringUtils.isNotEmpty(str)) {
        int addStart = str.indexOf("formatted_address\":");
        int addEnd = str.indexOf("\",\"business");
        if (addStart > 0 && addEnd > 0) {
            String address = str.substring(addStart + 20, addEnd);
            map = new HashMap<String, String>();
            map.put("address", address);
            return map;
        }
    }

    return null;

}

From source file:com.vmware.thinapp.common.util.AfUtil.java

/**
 * Attempt to extract a filename from the HTTP headers when accessing the
 * given URL.//  w  ww .j a  va 2  s . c o  m
 *
 * @param url URL to access
 * @return filename extracted from the Content-Disposition HTTP header, null
 *         if extraction fails.
 */
public static String getFilenameFromUrl(URL url) {
    String filename = null;

    if (url == null) {
        return null;
    }

    try {
        URLConnection connection = url.openConnection();
        connection.connect();

        // Pull out the Content-Disposition header if there is one
        String contentDisp = connection.getHeaderField(AfUtil.CONTENT_DISPOSITION);

        // Attempt to close the associated stream as we don't need it
        Closeables.closeQuietly(connection.getInputStream());

        // Attempt to extract the filename from the HTTP header
        filename = AfUtil.getFilenameFromContentDisposition(contentDisp);
    } catch (IOException ex) {
        // Unable to make the HTTP request to get the filename from the
        // message headers.
        // Do nothing, null will be returned.
    }
    return filename;
}

From source file:jfix.util.Urls.java

/**
 * Returns content from given url as string. The url can contain
 * username:password after the protocol, so that basic authorization is
 * possible.// www.j  av  a  2 s  . c om
 * 
 * Example for url with basic authorization:
 * 
 * http://username:password@www.domain.org/index.html
 */
public static String readString(String url, int timeout) {
    Reader reader = null;
    try {
        URLConnection uc = new URL(url).openConnection();
        if (uc instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) uc;
            httpConnection.setConnectTimeout(timeout * 1000);
            httpConnection.setReadTimeout(timeout * 1000);
        }
        Matcher matcher = Pattern.compile("://(\\w+:\\w+)@").matcher(url);
        if (matcher.find()) {
            String auth = matcher.group(1);
            String encoding = Base64.getEncoder().encodeToString(auth.getBytes());
            uc.setRequestProperty("Authorization", "Basic " + encoding);
        }
        String charset = (uc.getContentType() != null && uc.getContentType().contains("charset="))
                ? uc.getContentType().split("charset=")[1]
                : "utf-8";
        reader = new BufferedReader(new InputStreamReader(uc.getInputStream(), charset));
        StringBuilder sb = new StringBuilder();
        for (int chr; (chr = reader.read()) != -1;) {
            sb.append((char) chr);
        }
        return sb.toString();
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
}

From source file:com.sun.faces.generate.RenderKitSpecificationGenerator.java

public static void copyResourceToFile(String resourceName, File file) throws Exception {
    FileOutputStream fos = null;/*from w w  w .java  2s . co m*/
    BufferedInputStream bis = null;
    URL url = null;
    URLConnection conn = null;
    byte[] bytes = new byte[1024];
    int len = 0;

    fos = new FileOutputStream(file);
    url = getCurrentLoader(fos).getResource(resourceName);
    conn = url.openConnection();
    conn.setUseCaches(false);
    bis = new BufferedInputStream(conn.getInputStream());
    while (-1 != (len = bis.read(bytes, 0, 1024))) {
        fos.write(bytes, 0, len);
    }
    fos.close();
    bis.close();

}