Java Code Examples for java.net.URLConnection.getInputStream()

The following are Jave code examples for showing how to use getInputStream() of the java.net.URLConnection class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Parabot-317-API-Minified-OS-Scape   File: NetUtil.java   View Source Code Vote up 6 votes
public static String[] readPage(String url) {
    url = url.replaceAll(" ", "%20");
    ArrayList<String> lines = new ArrayList<String>();
    try {
        final URLConnection  con = createURLConnection(url);
        final BufferedReader in  = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String               line;
        while ((line = in.readLine()) != null) {
            lines.add(line);
        }
        in.close();
    } catch (Exception e) {
        System.out.println("Error reading page!");
    }
    return lines.toArray(new String[lines.size()]);
}
 
Example 2
Project: microbit   File: DownloadManager.java   View Source Code Vote up 6 votes
public long download(String sourceUrl, String destinationFile) {
    long objectSize = 0L;

    try {
        URL url = new URL(sourceUrl);
        URLConnection urlConnection = url.openConnection();
        InputStream is = urlConnection.getInputStream();
        OutputStream os = new FileOutputStream(new File(destinationFile));
        objectSize = IOUtils.copy(is, os);
        os.close();
        is.close();
    } catch(IOException ex) {
        Log.e(TAG, ex.toString());
    }

    return objectSize;
}
 
Example 3
Project: GitHub   File: MockWebServerTest.java   View Source Code Vote up 6 votes
/**
 * Throttle the request body by sleeping 500ms after every 3 bytes. With a 6-byte request, this
 * should yield one sleep for a total delay of 500ms.
 */
@Test public void throttleRequest() throws Exception {
  server.enqueue(new MockResponse()
      .throttleBody(3, 500, TimeUnit.MILLISECONDS));

  long startNanos = System.nanoTime();
  URLConnection connection = server.url("/").url().openConnection();
  connection.setDoOutput(true);
  connection.getOutputStream().write("ABCDEF".getBytes("UTF-8"));
  InputStream in = connection.getInputStream();
  assertEquals(-1, in.read());
  long elapsedNanos = System.nanoTime() - startNanos;
  long elapsedMillis = NANOSECONDS.toMillis(elapsedNanos);

  assertTrue(Util.format("Request + Response: %sms", elapsedMillis), elapsedMillis >= 500);
  assertTrue(Util.format("Request + Response: %sms", elapsedMillis), elapsedMillis < 1000);
}
 
Example 4
Project: lams   File: LamsSecurityUtil.java   View Source Code Vote up 6 votes
/**
    * Make a call to LAMS server.
    * 
    * @param serviceURL
    * @return resulted InputStream
    * @throws IOException
    */
   private static InputStream callLamsServer(String serviceURL) throws IOException {
URL url = new URL(serviceURL);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection)) {
    throw new IOException("Unable to open connection to: " + serviceURL);
}

HttpURLConnection httpConn = (HttpURLConnection) conn;

if (httpConn.getResponseCode() != HttpURLConnection.HTTP_OK) {
    throw new IOException("LAMS server responded with HTTP response code: " + httpConn.getResponseCode()
	    + ", HTTP response message: " + httpConn.getResponseMessage());
}

// InputStream is = url.openConnection().getInputStream();
InputStream is = conn.getInputStream();

return is;
   }
 
Example 5
Project: GIFKR   File: CalebKussmaul.java   View Source Code Vote up 6 votes
public static boolean refresh(){
	props 							= new Properties();
	try {
		URLConnection connection	= new URL("http://kussmaul.net/projects.properties").openConnection();
		connection.setConnectTimeout(1000);
		final InputStream in = connection.getInputStream();
		props.load(in);
		if(!props.containsKey("ServerIP"))
			throw new Exception("Something wrong with download");
		in.close();
		return true;
	} catch (Exception e) {
		e.printStackTrace();
		props						= getDefaultProperties();
		return false;
	}
}
 
Example 6
Project: McrmbCore_Sponge   File: HttpUtil.java   View Source Code Vote up 6 votes
/***
 * get请求mcrmbAPI
 * @param url API
 * @param reason 理由
 * @return json
 * @throws Exception HTTP请求异常
 */
public static JsonObject get(String url, String reason) throws IOException {
    if (McrmbPluginInfo.config.logApi) {
        McrmbCoreMain.info("发起" + reason + "请求: " + api + url);
    }
    StringBuilder builder = new StringBuilder();
    URLConnection con = new URL(api + url).openConnection();
    con.setRequestProperty("User-Agent", java_version);
    con.setRequestProperty("OS-Info", os);
    con.setConnectTimeout(25000);
    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String line;
    while ((line = reader.readLine()) != null) {
        builder.append(line);
    }
    reader.close();
    return new JsonParser().parse(builder.toString()).getAsJsonObject();
}
 
Example 7
Project: jetfuel-instagram   File: Info.java   View Source Code Vote up 6 votes
@Override
protected void mainFlow(UsecaseExecution<Parameters, InstagramResponse<User>> execution) throws Exception {

	String endpoint = String.format(
			"https://api.instagram.com/v1/users/%s/?access_token=%s",
			execution.params.id == null || execution.params.id.isEmpty()
					? "self"
					: execution.params.id,
			execution.params.access_token);

	URL url = new URL(endpoint);
	URLConnection connection = url.openConnection();
	InputStream is = connection.getInputStream();
	try {
		execution.result = MAPPER.readValue(is, new TypeReference<InstagramResponse<User>>() {
		});
	} finally {
		is.close();
	}
	execution.result_type = UsecaseResultType.SUCCESS;
}
 
Example 8
Project: jetfuel-instagram   File: RecentMedia.java   View Source Code Vote up 6 votes
@Override
protected void mainFlow(UsecaseExecution<RecentMedia.Parameters, InstagramResponse<List<Media>>> execution) throws Exception {

	String endpoint = String.format(
			"https://api.instagram.com/v1/tags/%s/media/recent?access_token=%s",
			execution.params.tag,
			execution.params.access_token);

	URL url = new URL(endpoint);
	URLConnection connection = url.openConnection();
	InputStream is = connection.getInputStream();
	try {
		execution.result = MAPPER.readValue(is, new TypeReference<InstagramResponse<List<Media>>>() {
		});
	} finally {
		is.close();
	}
	execution.result_type = UsecaseResultType.SUCCESS;
}
 
Example 9
Project: GitHub   File: MockWebServerTest.java   View Source Code Vote up 6 votes
/**
 * Throttle the request body by sleeping 500ms after every 3 bytes. With a 6-byte request, this
 * should yield one sleep for a total delay of 500ms.
 */
@Test public void throttleRequest() throws Exception {
  server.enqueue(new MockResponse()
      .throttleBody(3, 500, TimeUnit.MILLISECONDS));

  long startNanos = System.nanoTime();
  URLConnection connection = server.url("/").url().openConnection();
  connection.setDoOutput(true);
  connection.getOutputStream().write("ABCDEF".getBytes("UTF-8"));
  InputStream in = connection.getInputStream();
  assertEquals(-1, in.read());
  long elapsedNanos = System.nanoTime() - startNanos;
  long elapsedMillis = NANOSECONDS.toMillis(elapsedNanos);

  assertTrue(Util.format("Request + Response: %sms", elapsedMillis), elapsedMillis >= 500);
  assertTrue(Util.format("Request + Response: %sms", elapsedMillis), elapsedMillis < 1000);
}
 
Example 10
Project: OpenJSharp   File: AppletClassLoader.java   View Source Code Vote up 6 votes
private static byte[] getBytes(URL url) throws IOException {
    URLConnection uc = url.openConnection();
    if (uc instanceof java.net.HttpURLConnection) {
        java.net.HttpURLConnection huc = (java.net.HttpURLConnection) uc;
        int code = huc.getResponseCode();
        if (code >= java.net.HttpURLConnection.HTTP_BAD_REQUEST) {
            throw new IOException("open HTTP connection failed.");
        }
    }
    int len = uc.getContentLength();

    // Fixed #4507227: Slow performance to load
    // class and resources. [stanleyh]
    //
    // Use buffered input stream [stanleyh]
    InputStream in = new BufferedInputStream(uc.getInputStream());

    byte[] b;
    try {
        b = IOUtils.readFully(in, len, true);
    } finally {
        in.close();
    }
    return b;
}
 
Example 11
Project: ObsidianSuite   File: Downloader.java   View Source Code Vote up 6 votes
private void downloadZip(String link) throws MalformedURLException, IOException
{
	URL url = new URL(link);
	URLConnection conn = url.openConnection();
	InputStream is = conn.getInputStream();
	long max = conn.getContentLength();
	gui.setOutputText("Downloding file...");
	BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(new File("update.zip")));
	byte[] buffer = new byte[32 * 1024];
	int bytesRead = 0;
	int in = 0;
	while ((bytesRead = is.read(buffer)) != -1) {
		in += bytesRead;
		fOut.write(buffer, 0, bytesRead);
	}
	fOut.flush();
	fOut.close();
	is.close();
	gui.setOutputText("Download Complete!");

}
 
Example 12
Project: pac4j-plus   File: CommonHelper.java   View Source Code Vote up 5 votes
private static InputStream getInputStreamViaHttp(String name) {
    URLConnection con = null;
    try {
        URL url = new URL(name);
        con = url.openConnection();
        return con.getInputStream();
    } catch (IOException ex) {
        // Close the HTTP connection (if applicable).
        if (con instanceof HttpURLConnection) {
            ((HttpURLConnection) con).disconnect();
        }
        throw new TechnicalException(ex);
    }
}
 
Example 13
Project: RNLearn_Project1   File: ImageEditingManager.java   View Source Code Vote up 5 votes
private InputStream openBitmapInputStream() throws IOException {
  InputStream stream;
  if (isLocalUri(mUri)) {
    stream = mContext.getContentResolver().openInputStream(Uri.parse(mUri));
  } else {
    URLConnection connection = new URL(mUri).openConnection();
    stream = connection.getInputStream();
  }
  if (stream == null) {
    throw new IOException("Cannot open bitmap: " + mUri);
  }
  return stream;
}
 
Example 14
Project: incubator-netbeans   File: Utilities.java   View Source Code Vote up 5 votes
public static void projectDownload(String projectUrl, File projectZip) throws Exception {

        /* Temporary solution - download jEdit from internal location */
        OutputStream out = null;
        URLConnection conn;
        InputStream in = null;

        try {
            URL url = new URL(projectUrl);
            if (!projectZip.getParentFile().exists()) {
                projectZip.getParentFile().mkdirs();
            }
            out = new BufferedOutputStream(new FileOutputStream(projectZip));
            conn = url.openConnection();
            in = conn.getInputStream();
            byte[] buffer = new byte[1024];
            int numRead;
            while ((numRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, numRead);
            }
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException ioe) {
            }
        }
    }
 
Example 15
Project: MapAnalyst   File: OsmTileLoader.java   View Source Code Vote up 4 votes
@Override
public void run() {
    synchronized (tile) {
        if ((tile.isLoaded() && !tile.hasError()) || tile.isLoading())
            return;
        tile.loaded = false;
        tile.error = false;
        tile.loading = true;
    }
    try {
        URLConnection conn = loadTileFromOsm(tile);
        if (force) {
            conn.setUseCaches(false);
        }
        loadTileMetadata(tile, conn);
        if ("no-tile".equals(tile.getValue("tile-info"))) {
            tile.setError("No tile at this zoom level");
        } else {
            input = conn.getInputStream();
            try {
                tile.loadImage(input);
            } finally {
                input.close();
                input = null;
            }
        }
        tile.setLoaded(true);
        listener.tileLoadingFinished(tile, true);
    } catch (IOException e) {
        tile.setError(e.getMessage());
        listener.tileLoadingFinished(tile, false);
        if (input == null) {
            try {
                System.err.println("Failed loading " + tile.getUrl() +": "
                        +e.getClass() + ": " + e.getMessage());
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    } finally {
        tile.loading = false;
        tile.setLoaded(true);
    }
}
 
Example 16
Project: GradePoint   File: NetworkProcesser.java   View Source Code Vote up 4 votes
/**
 * 获取请求的html页面
 * @exception Exception 读写异常或网络异常
 * @return html文档字符串,utf-8编码
 */
public String getHtmlContent() throws Exception {
    // 构造URL
    URL realUrl = new URL(url);
    // 打开和URL之间的连接
    URLConnection conn = realUrl.openConnection();
    // 设置通用的请求头部属性
    conn.setRequestProperty("accept", "*/*");
    conn.setRequestProperty("connection", "Keep-Alive");
    conn.setRequestProperty("user-agent",
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36");
    conn.setRequestProperty("Accept-Charset", "utf-8");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    // 发送POST必须的设置
    conn.setDoOutput(true);
    conn.setDoInput(true);
    // 获取URLConnection对象对应的输出流
    PrintWriter out = new PrintWriter(conn.getOutputStream());
    // 写入请求参数
    out.print(this.param);
    // 刷新输出流的缓冲,即发送请求参数
    out.flush();
    // 获取请求的输入流(响应)
    InputStream ips = conn.getInputStream();
    // 构造字节数组输出流
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    // 缓冲块
    byte[] buffer = new byte[512];
    int len;
    while((len = ips.read(buffer)) != -1) {
        // 将缓冲块数据写入字节数组输出流
        bos.write(buffer, 0, len);
    }
    // 获取输出流对应的字节数组并转换成utf-8编码的字符串,即html文档
    String result = new String(bos.toByteArray(), "UTF-8");
    if(out != null){
        out.close();
    }
    if(bos != null) {
        bos.close();
    }
    if(ips != null) {
        ips.close();
    }
    return result;
}
 
Example 17
Project: X4J   File: Resources.java   View Source Code Vote up 4 votes
public static InputStream getUrlAsStream(String urlString) throws IOException {
  URL url = new URL(urlString);
  URLConnection conn = url.openConnection();
  return conn.getInputStream();
}
 
Example 18
Project: NBANDROID-V2   File: MavenDownloader.java   View Source Code Vote up 4 votes
public static void downloadFully(URL url, File target, JProgressBar progressBar) throws IOException {

        // We don't use the settings here explicitly, since HttpRequests picks up the network settings from studio directly.
        try {
            URLConnection connection = url.openConnection();
            if (connection instanceof HttpsURLConnection) {
                ((HttpsURLConnection) connection).setInstanceFollowRedirects(true);
                ((HttpsURLConnection) connection).setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; PPC; en-US; rv:1.3.1)");
                ((HttpsURLConnection) connection).setRequestProperty("Accept-Charset", "UTF-8");
                ((HttpsURLConnection) connection).setDoOutput(true);
                ((HttpsURLConnection) connection).setDoInput(true);
            }
            connection.setConnectTimeout(3000);
            connection.connect();
            int contentLength = connection.getContentLength();
            if (contentLength < 1) {
                throw new FileNotFoundException();
            }
            if (progressBar != null) {
                progressBar.setMinimum(0);
                progressBar.setMaximum(contentLength);
            }
            OutputStream dest = new FileOutputStream(target);
            InputStream in = connection.getInputStream();
            int count;
            int done = 0;
            byte data[] = new byte[BUFFER_SIZE];
            while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) {
                done += count;
                if (progressBar != null) {
                    progressBar.setValue(done);
                }
                dest.write(data, 0, count);
            }
            dest.close();
            in.close();
        } finally {
            if (target.length() == 0) {
                try {
                    target.delete();
                } catch (Exception e) {
                }
            }
        }
    }
 
Example 19
Project: sample.daytrader3   File: PingServlet2PDF.java   View Source Code Vote up 4 votes
/**
 * this is the main method of the servlet that will service all get requests.
 * @param request HttpServletRequest
 * @param responce HttpServletResponce
 **/
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
	PingBean ab;
	BufferedInputStream  bis = null; 
	BufferedOutputStream bos = null;
	try {
		ab = new PingBean();
		hitCount++;
		ab.setMsg("Hit Count: " + hitCount);
		req.setAttribute("ab", ab);

		ServletOutputStream out = res.getOutputStream();

		// MIME type for pdf doc
		res.setContentType( "application/pdf" );  

		//Open an InputStream to the PDF document    
		String fileURL = "http://localhost:9080/daytrader/WAS_V7_64-bit_performance.pdf";
		URL url = new URL ( fileURL );	    
		URLConnection conn = url.openConnection();
		bis = new BufferedInputStream(conn.getInputStream());

		//Transfer the InputStream (PDF Document) to OutputStream (servlet)
		bos = new BufferedOutputStream(out);
		byte[] buff = new byte[BUFFER_SIZE];
		int bytesRead; 
		// 	Simple read/write loop.
		while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
			bos.write(buff, 0, bytesRead);
		}



	}
	catch (Exception ex)
	{
		Log.error(
				ex,"PingServlet2Jsp.doGet(...): request error"); 
		res.sendError(
				500, 
				"PingServlet2Jsp.doGet(...): request error"
				+ ex.toString()); 

	}


	finally {
		if (bis != null)
			bis.close();
		if (bos != null)
			bos.close();
	}


}
 
Example 20
Project: HL4A   File: UrlModuleSourceProvider.java   View Source Code Vote up 4 votes
private static Reader getReader(URLConnection urlConnection)
throws IOException
{
    return new InputStreamReader(urlConnection.getInputStream(),
            getCharacterEncoding(urlConnection));
}