本文整理汇总了Java中java.net.URLConnection.getInputStream方法的典型用法代码示例。如果您正苦于以下问题:Java URLConnection.getInputStream方法的具体用法?Java URLConnection.getInputStream怎么用?Java URLConnection.getInputStream使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.net.URLConnection
的用法示例。
在下文中一共展示了URLConnection.getInputStream方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: mainFlow
import java.net.URLConnection; //导入方法依赖的package包/类
@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;
}
示例2: readPage
import java.net.URLConnection; //导入方法依赖的package包/类
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()]);
}
示例3: getBytes
import java.net.URLConnection; //导入方法依赖的package包/类
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;
}
示例4: download
import java.net.URLConnection; //导入方法依赖的package包/类
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;
}
示例5: throttleRequest
import java.net.URLConnection; //导入方法依赖的package包/类
/**
* 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);
}
示例6: callLamsServer
import java.net.URLConnection; //导入方法依赖的package包/类
/**
* 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;
}
示例7: refresh
import java.net.URLConnection; //导入方法依赖的package包/类
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;
}
}
示例8: get
import java.net.URLConnection; //导入方法依赖的package包/类
/***
* 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();
}
示例9: mainFlow
import java.net.URLConnection; //导入方法依赖的package包/类
@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;
}
示例10: downloadZip
import java.net.URLConnection; //导入方法依赖的package包/类
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!");
}
示例11: getInputStreamViaHttp
import java.net.URLConnection; //导入方法依赖的package包/类
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);
}
}
示例12: openBitmapInputStream
import java.net.URLConnection; //导入方法依赖的package包/类
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;
}
示例13: projectDownload
import java.net.URLConnection; //导入方法依赖的package包/类
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) {
}
}
}
示例14: run
import java.net.URLConnection; //导入方法依赖的package包/类
@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);
}
}
示例15: getHtmlContent
import java.net.URLConnection; //导入方法依赖的package包/类
/**
* 获取请求的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;
}