本文整理汇总了Java中java.net.HttpURLConnection.setReadTimeout方法的典型用法代码示例。如果您正苦于以下问题:Java HttpURLConnection.setReadTimeout方法的具体用法?Java HttpURLConnection.setReadTimeout怎么用?Java HttpURLConnection.setReadTimeout使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.net.HttpURLConnection
的用法示例。
在下文中一共展示了HttpURLConnection.setReadTimeout方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: ping
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Pings a given {@code url} for availability. Effectively sends a HEAD request and returns {@code true} if the response code is in
* the {@code 200} - {@code 399} range.
* @param url the url to be pinged.
* @param timeout_millis the timeout in millis for both the connection timeout and the response read timeout. Note that
* the total timeout is effectively two times the given timeout.
* @return {@code true} if the given {@code url} has returned response code within the range of {@code 200} - {@code 399} on a HEAD request, {@code false} otherwise
*/
public static boolean ping(final URL url, final int timeout_millis) {
try {
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(timeout_millis);
connection.setReadTimeout(timeout_millis);
connection.setRequestMethod(HEAD_REQUEST_METHOD);
final int response_code = connection.getResponseCode();
return HttpURLConnection.HTTP_OK <= response_code && response_code < HttpURLConnection.HTTP_BAD_REQUEST;
}
catch (IOException exception) {
return false;
}
}
示例2: initRuleSet
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public void initRuleSet() throws Exception{
InputStream fin = null;
String targetUrl=ContextHolder.getRequest().getRequestURL().toString();
String uri=ContextHolder.getRequest().getRequestURI();
int pos=targetUrl.indexOf(uri);
String contextPath=ContextHolder.getRequest().getContextPath();
if(StringUtils.isNotEmpty(contextPath)){
targetUrl=targetUrl.substring(0,pos)+contextPath+"/dorado/ide/config-rules.xml";
}else{
targetUrl=targetUrl.substring(0,pos)+"/dorado/ide/config-rules.xml";
}
URL url=new URL(targetUrl);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
try{
httpConnection.setConnectTimeout(10000);
httpConnection.setReadTimeout(10000);
httpConnection.setRequestMethod("GET");
fin=httpConnection.getInputStream();
ruleSet = ruleSetBuilder.buildRuleSet(fin);
}finally{
if(fin!=null)fin.close();
if(httpConnection!=null)httpConnection.disconnect();
}
}
示例3: getKeepAlive
import java.net.HttpURLConnection; //导入方法依赖的package包/类
@Test public void getKeepAlive() throws Exception {
server.enqueue(new MockResponse().setBody("ABC"));
// The request should work once and then fail
HttpURLConnection connection1 = urlFactory.open(server.url("/").url());
connection1.setReadTimeout(100);
InputStream input = connection1.getInputStream();
assertEquals("ABC", readAscii(input, Integer.MAX_VALUE));
server.shutdown();
try {
HttpURLConnection connection2 = urlFactory.open(server.url("").url());
connection2.setReadTimeout(100);
connection2.getInputStream();
fail();
} catch (ConnectException expected) {
}
}
示例4: rawWithAgent
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private String rawWithAgent(String url) {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.addRequestProperty("User-Agent", "Mozilla/4.76");
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.setDoOutput(true);
return IOUtils.toString(connection.getInputStream(), "UTF-8");
} catch (Exception e) {
JsonObject object = new JsonObject();
object.addProperty("success", false);
object.addProperty("cause", "Exception");
return object.toString();
}
}
示例5: prepareConnection
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Prepare the given HTTP connection.
* <p>The default implementation specifies POST as method,
* "application/x-java-serialized-object" as "Content-Type" header,
* and the given content length as "Content-Length" header.
* @param connection the HTTP connection to prepare
* @param contentLength the length of the content to send
* @throws IOException if thrown by HttpURLConnection methods
* @see java.net.HttpURLConnection#setRequestMethod
* @see java.net.HttpURLConnection#setRequestProperty
*/
protected void prepareConnection(HttpURLConnection connection, int contentLength) throws IOException {
if (this.connectTimeout >= 0) {
connection.setConnectTimeout(this.connectTimeout);
}
if (this.readTimeout >= 0) {
connection.setReadTimeout(this.readTimeout);
}
connection.setDoOutput(true);
connection.setRequestMethod(HTTP_METHOD_POST);
connection.setRequestProperty(HTTP_HEADER_CONTENT_TYPE, getContentType());
connection.setRequestProperty(HTTP_HEADER_CONTENT_LENGTH, Integer.toString(contentLength));
LocaleContext localeContext = LocaleContextHolder.getLocaleContext();
if (localeContext != null) {
Locale locale = localeContext.getLocale();
if (locale != null) {
connection.setRequestProperty(HTTP_HEADER_ACCEPT_LANGUAGE, StringUtils.toLanguageTag(locale));
}
}
if (isAcceptGzipEncoding()) {
connection.setRequestProperty(HTTP_HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
}
}
示例6: openConnection
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Opens an {@link HttpURLConnection} with parameters.
* @param url
* @return an open connection
* @throws IOException
*/
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
HttpURLConnection connection = createConnection(url);
int timeoutMs = request.getTimeoutMs();
connection.setConnectTimeout(timeoutMs);
connection.setReadTimeout(timeoutMs);
connection.setUseCaches(false);
connection.setDoInput(true);
// use caller-provided custom SslSocketFactory, if any, for HTTPS
if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory);
}
return connection;
}
示例7: downloadPlayerAvatar
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public void downloadPlayerAvatar(Player player) throws MalformedURLException, IOException {
URL url = new URL(player.avatarUrl);
HttpURLConnection httpConnection = (HttpURLConnection) (url.openConnection());
long completeFileSize = httpConnection.getContentLength();
httpConnection.setReadTimeout(15000);
File targetFile = new File("cache/" + player.getSteamId() + ".jpg");
java.io.BufferedInputStream is = new java.io.BufferedInputStream(httpConnection.getInputStream());
try (OutputStream outStream = new FileOutputStream(targetFile)) {
byte[] buffer = new byte[8 * 1024];
int bytesRead;
double downLoadFileSize = 0;
while ((bytesRead = is.read(buffer)) != -1) {
downLoadFileSize = downLoadFileSize + bytesRead;
outStream.write(buffer, 0, bytesRead);
}
}
}
示例8: notifyGCMServer
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public void notifyGCMServer(String urlStr, String key) {
if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Development) {
// In the development server, don't notify GCM
LOG.warning("Should notify the GCM server that new data is available, pinging URL "+urlStr);
} else {
try {
URL url = new URL(urlStr);
if (LOG.isLoggable(Level.INFO)) {
LOG.info("Pinging GCM at URL: "+url);
}
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(1000 * 30); // 30 seconds
connection.setRequestProperty("Authorization", "key="+key);
connection.connect();
int statusCode = connection.getResponseCode();
if (statusCode < 200 || statusCode >= 300) {
LOG.severe("Unexpected response code from GCM server: "+statusCode+". "+connection.getResponseMessage());
}
} catch (Exception ex) {
LOG.log(Level.SEVERE, "Unexpected error when pinging GCM server", ex);
}
}
}
示例9: configUrlConnection
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private static void configUrlConnection(HttpURLConnection urlConnection) {
urlConnection.setReadTimeout(TIMEOUT);
urlConnection.setConnectTimeout(TIMEOUT);
urlConnection.setUseCaches(false);
}
示例10: resolve
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public Record[] resolve(Domain domain, NetworkInfo info) throws IOException {
HttpURLConnection httpConn = (HttpURLConnection) new URL("http://119.29.29" +
".29/d?ttl=1&dn=" + domain.domain).openConnection();
httpConn.setConnectTimeout(BaseImageDownloader.DEFAULT_HTTP_CONNECT_TIMEOUT);
httpConn.setReadTimeout(10000);
if (httpConn.getResponseCode() != 200) {
return null;
}
int length = httpConn.getContentLength();
if (length <= 0 || length > 1024) {
return null;
}
InputStream is = httpConn.getInputStream();
byte[] data = new byte[length];
int read = is.read(data);
is.close();
if (read <= 0) {
return null;
}
String[] r1 = new String(data, 0, read).split(",");
if (r1.length != 2) {
return null;
}
try {
int ttl = Integer.parseInt(r1[1]);
String[] ips = r1[0].split(com.boohee.one.http.DnspodFree.IP_SPLIT);
if (ips.length == 0) {
return null;
}
Record[] records = new Record[ips.length];
long time = System.currentTimeMillis() / 1000;
for (int i = 0; i < ips.length; i++) {
records[i] = new Record(ips[i], 1, ttl, time);
}
return records;
} catch (Exception e) {
return null;
}
}
示例11: testServerClosesOutput
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private void testServerClosesOutput(SocketPolicy socketPolicy) throws Exception {
server.enqueue(new MockResponse().setBody("This connection won't pool properly")
.setSocketPolicy(socketPolicy));
MockResponse responseAfter = new MockResponse().setBody("This comes after a busted connection");
server.enqueue(responseAfter);
server.enqueue(responseAfter); // Enqueue 2x because the broken connection may be reused.
HttpURLConnection connection1 = urlFactory.open(server.url("/a").url());
connection1.setReadTimeout(100);
assertContent("This connection won't pool properly", connection1);
assertEquals(0, server.takeRequest().getSequenceNumber());
// Give the server time to enact the socket policy if it's one that could happen after the
// client has received the response.
Thread.sleep(500);
HttpURLConnection connection2 = urlFactory.open(server.url("/b").url());
connection2.setReadTimeout(100);
assertContent("This comes after a busted connection", connection2);
// Check that a fresh connection was created, either immediately or after attempting reuse.
RecordedRequest requestAfter = server.takeRequest();
if (server.getRequestCount() == 3) {
requestAfter = server.takeRequest(); // The failure consumed a response.
}
// sequence number 0 means the HTTP socket connection was not reused
assertEquals(0, requestAfter.getSequenceNumber());
}
示例12: createConnection
import java.net.HttpURLConnection; //导入方法依赖的package包/类
protected HttpURLConnection createConnection(String url, Object extra) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(Uri.encode(url, ALLOWED_URI_CHARS))
.openConnection();
conn.setConnectTimeout(this.connectTimeout);
conn.setReadTimeout(this.readTimeout);
return conn;
}
示例13: post
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Post请求
*
* @param url
* @param params
* @param https
* @return
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws KeyManagementException
*/
public static String post(String url, String body, boolean https) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
// 创建链接
URL u = new URL(url);
HttpURLConnection http = (HttpURLConnection) u.openConnection();
// 连接超时
http.setConnectTimeout(10000);
http.setReadTimeout(10000);
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type","application/json");
if(https) {
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, new TrustManager[]{new MyX509TrustManager()}, new SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
((HttpsURLConnection)http).setSSLSocketFactory(ssf);
}
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
// 写入参数
try (OutputStream out = http.getOutputStream()) {
out.write(body.getBytes(DEFAULT_CHARSET));
out.flush();
}
// 获取返回
StringBuilder sb = new StringBuilder();
try (InputStream is = http.getInputStream()) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, DEFAULT_CHARSET))) {
String str = null;
while((str = reader.readLine()) != null) {
sb.append(str);str = null;
}
}
}
// 关闭链接
if (http != null) {
http.disconnect();
}
return sb.toString();
}
示例14: JSONSource
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public JSONSource(Uri uri) throws IOException, JSONException {
String scheme = uri.getScheme();
if (IDataSource.SCHEME_HTTP_TAG.equalsIgnoreCase(scheme) || IDataSource.SCHEME_HTTPS_TAG.equalsIgnoreCase(scheme)) {
HttpURLConnection conn = (HttpURLConnection) new URL(uri.toString()).openConnection();
conn.setConnectTimeout(6000);
conn.setReadTimeout(6000);
init(conn.getInputStream());
} else if (IDataSource.SCHEME_FILE_TAG.equalsIgnoreCase(scheme)) {
init(new FileInputStream(uri.getPath()));
}
}
示例15: createConnection
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private HttpURLConnection createConnection(URL url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(DetectLanguage.timeout);
conn.setReadTimeout(DetectLanguage.timeout);
conn.setUseCaches(false);
String version = getClass().getPackage().getImplementationVersion();
conn.setRequestProperty("User-Agent", AGENT + '/' + version);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Accept-Charset", CHARSET);
return conn;
}