本文整理匯總了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;
}