本文整理汇总了Java中java.net.URLConnection.setReadTimeout方法的典型用法代码示例。如果您正苦于以下问题:Java URLConnection.setReadTimeout方法的具体用法?Java URLConnection.setReadTimeout怎么用?Java URLConnection.setReadTimeout使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.net.URLConnection
的用法示例。
在下文中一共展示了URLConnection.setReadTimeout方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: checkRedirect
import java.net.URLConnection; //导入方法依赖的package包/类
private static URLConnection checkRedirect(URLConnection conn, int timeout) throws IOException {
if (conn instanceof HttpURLConnection) {
conn.connect();
int code = ((HttpURLConnection) conn).getResponseCode();
if (code == HttpURLConnection.HTTP_MOVED_TEMP
|| code == HttpURLConnection.HTTP_MOVED_PERM) {
// in case of redirection, try to obtain new URL
String redirUrl = conn.getHeaderField("Location"); //NOI18N
if (null != redirUrl && !redirUrl.isEmpty()) {
//create connection to redirected url and substitute original conn
URL redirectedUrl = new URL(redirUrl);
URLConnection connRedir = redirectedUrl.openConnection();
// XXX is this neede
connRedir.setRequestProperty("User-Agent", "NetBeans"); // NOI18N
connRedir.setConnectTimeout(timeout);
connRedir.setReadTimeout(timeout);
if (connRedir instanceof HttpsURLConnection) {
NetworkAccess.initSSL((HttpsURLConnection) connRedir);
}
return connRedir;
}
}
}
return conn;
}
示例2: getRequest
import java.net.URLConnection; //导入方法依赖的package包/类
@Override
public String getRequest(ApiParameter... apiParameters) {
String params = getParameters(apiParameters);
try {
URL request = new URL(BASE_URL + params);
URLConnection connection = request.openConnection();
connection.setConnectTimeout(timeOut);
connection.setReadTimeout(timeOut);
InputStreamReader inputStream = new InputStreamReader(connection.getInputStream(), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStream);
StringBuilder responseBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
responseBuilder.append(line);
}
bufferedReader.close();
return responseBuilder.toString();
} catch (IOException e) {
throw new AlphaVantageException("failure sending request", e);
}
}
示例3: downloadFile
import java.net.URLConnection; //导入方法依赖的package包/类
/** 문자열 path를 가지고 파일을 다운 받아 바이트 배열로 바꿔주는 메서드.
* https://stackoverflow.com/questions/2295221/java-net-url-read-stream-to-byte 소스 코드 참고
* @param path
* @return
*/
public static byte[] downloadFile(String path)
{
try {
URL url = new URL(path);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(1000);
conn.setReadTimeout(1000);
conn.connect();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(conn.getInputStream(), baos);
return baos.toByteArray();
}
catch (IOException e)
{
return null;
}
}
示例4: createConnectionToURL
import java.net.URLConnection; //导入方法依赖的package包/类
/**
* Create URLConnection instance.
*
* @param url to what url
* @param requestHeaders additional request headers
* @return connection instance
* @throws IOException when url is invalid or failed to establish connection
*/
public static URLConnection createConnectionToURL(final String url, final Map<String, String> requestHeaders) throws IOException {
final URL connectionURL = URLUtility.stringToUrl(url);
if (connectionURL == null) {
throw new IOException("Invalid url format: " + url);
}
final URLConnection urlConnection = connectionURL.openConnection();
urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
urlConnection.setReadTimeout(READ_TIMEOUT);
if (requestHeaders != null) {
for (final Map.Entry<String, String> entry : requestHeaders.entrySet()) {
urlConnection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
return urlConnection;
}
示例5: getResponse
import java.net.URLConnection; //导入方法依赖的package包/类
public static String getResponse(String req, int timeOut, String userAgent, String encoding) throws IOException
{
URL url = new URL(req);
URLConnection conn = url.openConnection();
if (!Helper.isEmpty(userAgent))
conn.setRequestProperty("User-Agent", userAgent);
if (timeOut > 0)
conn.setReadTimeout(timeOut);
// conn.setRequestProperty("Accept-Language",
// "de,de-de;q=0.8,en;q=0.5,en-us;q=0.3");
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding));
String line = "";
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
is.close();
return sb.toString();
}
示例6: startElement
import java.net.URLConnection; //导入方法依赖的package包/类
@SuppressWarnings("nls")
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
if( localName.equalsIgnoreCase("a") ) //$NON-NLS-1$
{
String szURL = attributes.getValue("href"); //$NON-NLS-1$
URL relurl = null;
relurl = URLUtils.newURL(url, szURL);
if( !relurl.getProtocol().startsWith("http") || !robot.isAllowed(relurl) )
{
return;
}
if( LOGGER.isDebugEnabled() )
{
LOGGER.debug("Indexing:" + relurl); //$NON-NLS-1$
}
try
{
URLConnection urlcon = relurl.openConnection();
urlcon.setConnectTimeout(URL_TIMEOUT);
urlcon.setReadTimeout(URL_TIMEOUT);
try( InputStream inp = urlcon.getInputStream() )
{
MimeEntry mimeType = getMimeEntryFromContentType(urlcon.getContentType());
extractTextFromStream(getExtractors(mimeType), inp, mimeType, buf);
}
}
catch( Exception e )
{
if( LOGGER.isDebugEnabled() )
{
LOGGER.debug("Error indexing second level url:" + relurl, e);
}
}
}
}
示例7: netCheck
import java.net.URLConnection; //导入方法依赖的package包/类
public static boolean netCheck(String[] testURLs) {
for (String testURL : testURLs) {
try {
URL url = new URL(testURL);
URLConnection conn = (URLConnection)url.openConnection();
conn.setConnectTimeout(TemplateConstants.CONN_SHORT_TIMEOUT);
conn.setReadTimeout(TemplateConstants.READ_SHORT_TIMEOUT);
conn.getContent();
return true;
} catch (Exception e) {
System.out.println("failed to connect to " + testURL);
}
}
return false;
}
示例8: readUrl
import java.net.URLConnection; //导入方法依赖的package包/类
public static String readUrl(final URL url) throws IOException
{
final URLConnection urlConnection = url.openConnection();
try {
urlConnection.setConnectTimeout(CONNECT_TIMEOUT);
urlConnection.setReadTimeout(READ_TIMEOUT);
final StringBuilder stringBuilder = new StringBuilder();
final BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
int read;
final char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
stringBuilder.append(chars, 0, read);
return stringBuilder.toString();
} finally {
if (urlConnection instanceof HttpURLConnection)
((HttpURLConnection)urlConnection).disconnect();
}
}
示例9: getBitmapFromUrl
import java.net.URLConnection; //导入方法依赖的package包/类
private Bitmap getBitmapFromUrl(String url) {
Bitmap bitmap = null;
try {
URLConnection conn = new URL(url).openConnection();
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setReadTimeout(READ_TIMEOUT);
bitmap = BitmapFactory.decodeStream((InputStream) conn.getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
示例10: uploadURL
import java.net.URLConnection; //导入方法依赖的package包/类
private static URL uploadURL(URL url) throws IOException {
assert(!EventQueue.isDispatchThread());
File tmpFile = File.createTempFile("loading", ".html"); //NOI18N
tmpFile.deleteOnExit();
FileOutputStream fw = new FileOutputStream(tmpFile);
try{
URLConnection conn = url.openConnection();
conn.setReadTimeout(200000);
conn.setDoOutput(false);
conn.setDoInput(true);
conn.setRequestProperty("User-Agent", "NetBeans"); //NOI18N
InputStream is = conn.getInputStream();
if (is == null) {
throw new IOException("Null input stream from "+conn);
}
try{
while(true) {
int ch = is.read();
if (ch == -1) {
break;
}
fw.write(ch);
}
}finally{
is.close();
}
}finally{
fw.close();
}
return Utilities.toURI(tmpFile).toURL();
}
示例11: getInputStream
import java.net.URLConnection; //导入方法依赖的package包/类
public static InputStream getInputStream(Context context, Uri uri) throws IOException {
InputStream inputStream;
if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(uri.getScheme())
|| ContentResolver.SCHEME_ANDROID_RESOURCE.equals(uri.getScheme())
|| ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
inputStream = context.getContentResolver().openInputStream(uri);
} else {
URLConnection urlConnection = new URL(uri.toString()).openConnection();
urlConnection.setConnectTimeout(URLCONNECTION_CONNECTION_TIMEOUT_MS);
urlConnection.setReadTimeout(URLCONNECTION_READ_TIMEOUT_MS);
inputStream = urlConnection.getInputStream();
}
return new BufferedInputStream(inputStream);
}
示例12: setURLConnectionDefaults
import java.net.URLConnection; //导入方法依赖的package包/类
/**
* Sets some default settings for {@link URLConnection}s, e.g. timeouts.
*
* @param connection
*/
public static void setURLConnectionDefaults(URLConnection connection) {
if (connection == null) {
throw new IllegalArgumentException("url must not be null!");
}
connection.setConnectTimeout(TIMEOUT_URL_CONNECTION);
connection.setReadTimeout(READ_TIMEOUT);
}
示例13: createURLConnection
import java.net.URLConnection; //导入方法依赖的package包/类
/**
* Creates and configures a new URL connection to the JSON-RPC 2.0
* server endpoint according to the session settings.
*
* @return The URL connection, configured and ready for output (HTTP
* POST).
*
* @throws JSONRPC2SessionException If the URL connection couldn't be
* created or configured.
*/
private URLConnection createURLConnection()
throws JSONRPC2SessionException {
// Open HTTP connection
URLConnection con = null;
try {
// Use proxy?
if (options.getProxy() != null)
con = url.openConnection(options.getProxy());
else
con = url.openConnection();
} catch (IOException e) {
throw new JSONRPC2SessionException(
"Network exception: " + e.getMessage(),
JSONRPC2SessionException.NETWORK_EXCEPTION,
e);
}
con.setConnectTimeout(options.getConnectTimeout());
con.setReadTimeout(options.getReadTimeout());
applyHeaders(con);
// Set POST mode
con.setDoOutput(true);
// Set trust all certs SSL factory?
if (con instanceof HttpsURLConnection && options.trustsAllCerts()) {
if (trustAllSocketFactory == null)
throw new JSONRPC2SessionException("Couldn't obtain trust-all SSL socket factory");
((HttpsURLConnection)con).setSSLSocketFactory(trustAllSocketFactory);
}
// Apply connection configurator?
if (connectionConfigurator != null)
connectionConfigurator.configure((HttpURLConnection)con);
HttpAuth httpAuth = new HttpAuth();
con = httpAuth.tryDigestAuthentication((HttpURLConnection) con, httpLogin, httpPass,
options, connectionConfigurator);
return con;
}
示例14: getRobotPaths
import java.net.URLConnection; //导入方法依赖的package包/类
@SuppressWarnings("nls")
protected void getRobotPaths()
{
if( disallowedPaths != null )
{
return;
}
disallowedPaths = new HashSet<String>();
allowedPaths = new HashSet<String>();
try
{
URLConnection connection = robot.openConnection();
connection.setConnectTimeout((int) TimeUnit.MINUTES.toMillis(1));
connection.setReadTimeout((int) TimeUnit.MINUTES.toMillis(1));
try( BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())) )
{
String line = reader.readLine();
while( line != null && disallowedPaths.size() == 0 )
{
if( line.indexOf("User-agent:") >= 0 && line.indexOf('*') >= 0 )
{
line = reader.readLine();
while( line != null && line.indexOf("User-agent:") < 0 )
{
int comment = line.indexOf('#');
if( comment >= 0 )
{
line = line.substring(0, comment);
}
// expecting colon plus space plus value, eg
// "Allow: meaningful"
// but avoid lines which simply read "Allow:" (ie,
// nothing after colon)
int collon = line.indexOf(':');
if( collon >= 0 && line.length() >= collon + 2 )
{
if( line.indexOf("Disallow:") >= 0 )
{
String disallow = line.substring(collon + 2);
disallowedPaths.add(disallow);
}
else if( line.indexOf("Allow:") >= 0 )
{
String allow = line.substring(collon + 2);
allowedPaths.add(allow);
}
}
line = reader.readLine();
}
}
line = reader.readLine();
}
}
}
catch( IOException ie )
{
LOGGER.info(robot + " does not exist");
}
}
示例15: getInputStreamOfURL
import java.net.URLConnection; //导入方法依赖的package包/类
public InputStream getInputStreamOfURL(URL downloadURL, Proxy proxy) throws IOException{
URLConnection ucn = null;
// loop until no more redirections are
for (;;) {
if (Thread.currentThread().isInterrupted()) {
return null;
}
if(proxy != null) {
ucn = downloadURL.openConnection(proxy);
} else {
ucn = downloadURL.openConnection();
}
HttpURLConnection hucn = doConfigureURLConnection(ucn);
if(Thread.currentThread().isInterrupted())
return null;
ucn.connect();
int rc = hucn.getResponseCode();
boolean isRedirect =
rc == HttpURLConnection.HTTP_MOVED_TEMP ||
rc == HttpURLConnection.HTTP_MOVED_PERM;
if (!isRedirect) {
break;
}
String addr = hucn.getHeaderField(HTTP_REDIRECT_LOCATION);
URL newURL = new URL(addr);
if (!downloadURL.getProtocol().equalsIgnoreCase(newURL.getProtocol())) {
throw new ResourceRedirectException(newURL);
}
downloadURL = newURL;
}
ucn.setReadTimeout(10000);
InputStream is = ucn.getInputStream();
streamLength = ucn.getContentLength();
effectiveURL = ucn.getURL();
return is;
}