本文整理汇总了Java中java.net.URLConnection.setConnectTimeout方法的典型用法代码示例。如果您正苦于以下问题:Java URLConnection.setConnectTimeout方法的具体用法?Java URLConnection.setConnectTimeout怎么用?Java URLConnection.setConnectTimeout使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.net.URLConnection
的用法示例。
在下文中一共展示了URLConnection.setConnectTimeout方法的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: 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;
}
示例3: handleImageContent
import java.net.URLConnection; //导入方法依赖的package包/类
public TextMessage handleImageContent(String id){
String filepath = new File("/opt/tomcat/webapps/ROOT/downloaded.jpg").getAbsolutePath();
file = new File(filepath);
try {
URL urlP = new URL("https://api.line.me/v2/bot/message/" + id + "/content");
URLConnection conn = urlP.openConnection();
conn.setRequestProperty("Authorization", "Bearer {ZzEeHlFeiIA/C4TUvl3E/IuYW8TIBEdAr3xzZCgHuURivuycKWOiPGBp5oFqLyHSh/YkUFgm4eGGkVuo4WkOvhUwKdgCbFnO6ltoV/oMU7uJaZAbgM+RqeTo8LAbdjlId0TGTdPe6H0QyfzzoJyppgdB04t89/1O/w1cDnyilFU=}");
conn.setConnectTimeout(5 * 1000); // Tak tambahin sendiri
BufferedImage img = ImageIO.read(conn.getInputStream());
ImageIO.write(img, "jpg", file);
} catch (Exception e) {
e.printStackTrace();
}
byte[] buff = getBytesFromFile(file);
String response_faceAPI = doFacePlusAPI(buff);
TextMessage textMessage;
textMessage = processJsonFaceApi(response_faceAPI);
return textMessage;
}
示例4: 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;
}
示例5: 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;
}
}
示例6: resolve
import java.net.URLConnection; //导入方法依赖的package包/类
/**
* @param type the ec2 hostname type to discover.
* @return the appropriate host resolved from ec2 meta-data, or null if it cannot be obtained.
* @see CustomNameResolver#resolveIfPossible(String)
*/
@SuppressForbidden(reason = "We call getInputStream in doPrivileged and provide SocketPermission")
public InetAddress[] resolve(Ec2HostnameType type) throws IOException {
InputStream in = null;
String metadataUrl = AwsEc2ServiceImpl.EC2_METADATA_URL + type.ec2Name;
try {
URL url = new URL(metadataUrl);
logger.debug("obtaining ec2 hostname from ec2 meta-data url {}", url);
URLConnection urlConnection = SocketAccess.doPrivilegedIOException(url::openConnection);
urlConnection.setConnectTimeout(2000);
in = SocketAccess.doPrivilegedIOException(urlConnection::getInputStream);
BufferedReader urlReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
String metadataResult = urlReader.readLine();
if (metadataResult == null || metadataResult.length() == 0) {
throw new IOException("no gce metadata returned from [" + url + "] for [" + type.configName + "]");
}
// only one address: because we explicitly ask for only one via the Ec2HostnameType
return new InetAddress[] { InetAddress.getByName(metadataResult) };
} catch (IOException e) {
throw new IOException("IOException caught when fetching InetAddress from [" + metadataUrl + "]", e);
} finally {
IOUtils.closeWhileHandlingException(in);
}
}
示例7: 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();
}
示例8: 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;
}
示例9: createURLConnection
import java.net.URLConnection; //导入方法依赖的package包/类
public static URLConnection createURLConnection(String url) {
try {
final URL address = new URL(url);
final URLConnection connection = address.openConnection();
connection.addRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0");
connection.setConnectTimeout(5000);
connection.setRequestProperty("Content-Type", "image/png");
return connection;
} catch (IOException ex) {
System.out.println("Error creating connection!");
ex.printStackTrace();
}
return null;
}
示例10: getUpdateProperties
import java.net.URLConnection; //导入方法依赖的package包/类
private Properties getUpdateProperties(URL updateUrl) throws IOException {
URLConnection connection = updateUrl.openConnection();
connection.setConnectTimeout(3 * 1000);
InputStream in = connection.getInputStream();
try {
Properties props = new Properties();
props.load(connection.getInputStream());
return props;
} finally {
if (in != null) {
in.close();
}
}
}
示例11: save
import java.net.URLConnection; //导入方法依赖的package包/类
/**
* 上传文件
*
* @throws IllegalStateException
* @throws IOException
*/
protected void save() throws IllegalStateException, IOException {
// 构造URL
URL url = new URL(fileUrl);
// 打开连接
URLConnection con = url.openConnection();
// 设置请求超时为5s
con.setConnectTimeout(5 * 1000);
// 输入流
InputStream is = con.getInputStream();
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 获取文件mime类型
contentType = con.getContentType();
// 通过Mime类型获取文件类型
fileSuffix = ContentTypeUtil.getFileTypeByMimeType(contentType);
// 路径
path = UploadUtil.getPath(fileSuffix);
// 文件名
filename = UploadUtil.getFileName();
// 全路径
filePath = path + filename + "." + fileSuffix;
// 访问地址
webURL = UploadUtil.getURL(fileSuffix) + filename + "." + fileSuffix;
// 输出的文件流
OutputStream os = new FileOutputStream(filePath);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
isUpload = true;
}
示例12: downloadFully
import java.net.URLConnection; //导入方法依赖的package包/类
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) {
}
}
}
}
示例13: connect
import java.net.URLConnection; //导入方法依赖的package包/类
/**
* The connection establishment is attempted multiple times and is given up
* only on the last failure. Instead of connecting with a timeout of
* X, we try connecting with a timeout of x < X but multiple times.
*/
private void connect(URLConnection connection, int connectionTimeout)
throws IOException {
int unit = 0;
if (connectionTimeout < 0) {
throw new IOException("Invalid timeout "
+ "[timeout = " + connectionTimeout + " ms]");
} else if (connectionTimeout > 0) {
unit = Math.min(UNIT_CONNECT_TIMEOUT, connectionTimeout);
}
long startTime = Time.monotonicNow();
long lastTime = startTime;
int attempts = 0;
// set the connect timeout to the unit-connect-timeout
connection.setConnectTimeout(unit);
while (true) {
try {
attempts++;
connection.connect();
break;
} catch (IOException ioe) {
long currentTime = Time.monotonicNow();
long retryTime = currentTime - startTime;
long leftTime = connectionTimeout - retryTime;
long timeSinceLastIteration = currentTime - lastTime;
// throw an exception if we have waited for timeout amount of time
// note that the updated value if timeout is used here
if (leftTime <= 0) {
int retryTimeInSeconds = (int) retryTime/1000;
LOG.error("Connection retry failed with " + attempts +
" attempts in " + retryTimeInSeconds + " seconds");
throw ioe;
}
// reset the connect timeout for the last try
if (leftTime < unit) {
unit = (int)leftTime;
// reset the connect time out for the final connect
connection.setConnectTimeout(unit);
}
if (timeSinceLastIteration < unit) {
try {
// sleep the left time of unit
sleep(unit - timeSinceLastIteration);
} catch (InterruptedException e) {
LOG.warn("Sleep in connection retry get interrupted.");
if (stopped) {
return;
}
}
}
// update the total remaining connect-timeout
lastTime = Time.monotonicNow();
}
}
}
示例14: updateData
import java.net.URLConnection; //导入方法依赖的package包/类
public void updateData(ResultBeatmap rb) {
if (!rb.equals(lastMap)){
lastMap = rb;
lblImg.setIcon(null);
lblImg.setText("Waiting...");
lblImg.setText("");
lblName.setText(decode(rb.getArtist()) + " - " + decode(rb.getTitle()));
lblCreator.setText(decode(rb.getCreator()));
lblStatus.setText("Status not implemented");
String tagsStr = "";
String[] tags = rb.getTags();
for (int i = 0; i < tags.length; i++){
tagsStr += tags[i];
if (i != tags.length - 1){
tagsStr += ", ";
}
}
lblTags.setText("Tags: " + tagsStr);
if (rb.getThumbData().isEmpty()){
try {
lblImg.setForeground(Color.BLACK);
lblImg.setText("Loading thumb...");
URL url = new URL(rb.getThumbUrl());
URLConnection conn = url.openConnection();
conn.setConnectTimeout(100);
conn.setReadTimeout(100);
lblImg.setText("");
lblImg.setIcon(new ImageIcon(ImageIO.read(conn.getInputStream())));
} catch (Exception e){
lblImg.setForeground(Color.RED);
lblImg.setText("Thumb Fetch Error");
}
} else {
lblImg.setIcon(new ImageIcon(Base64.decodeBase64(rb.getThumbData())));
}
}
}
示例15: createAUResolver
import java.net.URLConnection; //导入方法依赖的package包/类
/** Entity resolver that knows about AU DTDs, so no network is needed.
* @author Jesse Glick
*/
public static EntityResolver createAUResolver() {
return new EntityResolver() {
@Override
public InputSource resolveEntity(String publicID, String systemID) throws IOException, SAXException {
if ("-//NetBeans//DTD Autoupdate Catalog 1.0//EN".equals(publicID)) { // NOI18N
return new InputSource(XMLUtil.class.getResource("resources/autoupdate-catalog-1_0.dtd").toString()); // NOI18N
} else if ("-//NetBeans//DTD Autoupdate Module Info 1.0//EN".equals(publicID)) { // NOI18N
return new InputSource(XMLUtil.class.getResource("resources/autoupdate-info-1_0.dtd").toString()); // NOI18N
} else if ("-//NetBeans//DTD Autoupdate Catalog 2.0//EN".equals(publicID)) { // NOI18N
return new InputSource(XMLUtil.class.getResource("resources/autoupdate-catalog-2_0.dtd").toString()); // NOI18N
} else if ("-//NetBeans//DTD Autoupdate Module Info 2.0//EN".equals(publicID)) { // NOI18N
return new InputSource(XMLUtil.class.getResource("resources/autoupdate-info-2_0.dtd").toString()); // NOI18N
} else if ("-//NetBeans//DTD Autoupdate Catalog 2.2//EN".equals(publicID)) { // NOI18N
return new InputSource(XMLUtil.class.getResource("resources/autoupdate-catalog-2_2.dtd").toString()); // NOI18N
} else if ("-//NetBeans//DTD Autoupdate Module Info 2.2//EN".equals(publicID)) { // NOI18N
return new InputSource(XMLUtil.class.getResource("resources/autoupdate-info-2_2.dtd").toString()); // NOI18N
} else if ("-//NetBeans//DTD Autoupdate Catalog 2.3//EN".equals(publicID)) { // NOI18N
return new InputSource(XMLUtil.class.getResource("resources/autoupdate-catalog-2_3.dtd").toString()); // NOI18N
} else if ("-//NetBeans//DTD Autoupdate Module Info 2.3//EN".equals(publicID)) { // NOI18N
return new InputSource(XMLUtil.class.getResource("resources/autoupdate-info-2_3.dtd").toString()); // NOI18N
} else if ("-//NetBeans//DTD Autoupdate Catalog 2.4//EN".equals(publicID)) { // NOI18N
return new InputSource(XMLUtil.class.getResource("resources/autoupdate-catalog-2_4.dtd").toString()); // NOI18N
} else if ("-//NetBeans//DTD Autoupdate Module Info 2.4//EN".equals(publicID)) { // NOI18N
return new InputSource(XMLUtil.class.getResource("resources/autoupdate-info-2_4.dtd").toString()); // NOI18N
} else if ("-//NetBeans//DTD Autoupdate Catalog 2.5//EN".equals(publicID)) { // NOI18N
return new InputSource(XMLUtil.class.getResource("resources/autoupdate-catalog-2_5.dtd").toString()); // NOI18N
} else if ("-//NetBeans//DTD Autoupdate Module Info 2.5//EN".equals(publicID)) { // NOI18N
return new InputSource(XMLUtil.class.getResource("resources/autoupdate-info-2_5.dtd").toString()); // NOI18N
} else if ("-//NetBeans//DTD Autoupdate Catalog 2.6//EN".equals(publicID)) { // NOI18N
return new InputSource(XMLUtil.class.getResource("resources/autoupdate-catalog-2_6.dtd").toString()); // NOI18N
} else if ("-//NetBeans//DTD Autoupdate Catalog 2.7//EN".equals(publicID)) { // NOI18N
return new InputSource(XMLUtil.class.getResource("resources/autoupdate-catalog-2_7.dtd").toString()); // NOI18N
} else if ("-//NetBeans//DTD Autoupdate Module Info 2.7//EN".equals(publicID)) { // NOI18N
return new InputSource(XMLUtil.class.getResource("resources/autoupdate-info-2_7.dtd").toString()); // NOI18N
} else {
if (systemID.endsWith(".dtd")) { // NOI18N
return new InputSource(new ByteArrayInputStream(new byte[0]));
}
URL u = new URL(systemID);
URLConnection oc = u.openConnection();
oc.setConnectTimeout(5000);
return new InputSource(oc.getInputStream());
}
}
};
}