本文整理汇总了Java中java.net.HttpURLConnection.setConnectTimeout方法的典型用法代码示例。如果您正苦于以下问题:Java HttpURLConnection.setConnectTimeout方法的具体用法?Java HttpURLConnection.setConnectTimeout怎么用?Java HttpURLConnection.setConnectTimeout使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.net.HttpURLConnection
的用法示例。
在下文中一共展示了HttpURLConnection.setConnectTimeout方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: AddrCanConnect
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* 链接是否可以被请求
*
* @param url 地址
* @param timeout 超时,单位毫秒
* @return true | false
*/
public static boolean AddrCanConnect(String url, int timeout) {
if (StringUtil.isEmpty(url)) {
return false;
}
boolean canConnect = false;
try {
URL urlStr = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlStr.openConnection();
connection.setUseCaches(false);
connection.setConnectTimeout(timeout);
int state = connection.getResponseCode();
if (state == HttpURLConnection.HTTP_OK) {
canConnect = true;
}
} catch (Exception ex) {
ex.printStackTrace();
}
return canConnect;
}
示例2: downloadApiJar
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public void downloadApiJar(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3 * 1000);
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
conn.setRequestProperty("Authorization", "Basic " + AUTHOR);
InputStream inputStream = conn.getInputStream();
byte[] getData = readInputStream(inputStream);
File saveDir = new File(API_DIR_PATH);
if (!saveDir.exists()) {
saveDir.mkdir();
}
File file = new File(API_JAR_PATH);
file.deleteOnExit();
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
if (fos != null) {
fos.close();
}
if (inputStream != null) {
inputStream.close();
}
logger.info(url + " download success");
}
示例3: 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;
}
示例4: checkConnection
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* <pre>
* 描述: 判断服务连通性
* @author yi.zhang
* 时间: 2017年4月19日 下午6:00:40
* @param url 请求URL
* @param auth 认证信息(username+":"+password)
* @return (true:连接成功,false:连接失败)
* </pre>
*/
public static boolean checkConnection(String url,String auth){
boolean flag = false;
try {
HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
connection.setConnectTimeout(5*1000);
if(auth!=null&&!"".equals(auth)){
String authorization = "Basic "+new String(Base64.encodeBase64(auth.getBytes()));
connection.setRequestProperty("Authorization", authorization);
}
connection.connect();
if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
flag = true;
}
connection.disconnect();
}catch (Exception e) {
logger.error("--Server Connect Error !",e);
}
return flag;
}
示例5: makeRequest
import java.net.HttpURLConnection; //导入方法依赖的package包/类
protected Response makeRequest(String url, DownZ.Method m, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
URL mUrl = new URL(url);
conn = (HttpURLConnection) mUrl.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(TIMEOUT);
/* time in milliseconds */
switch (m) {
case GET:
conn.setRequestMethod("GET");
break;
case POST:
conn.setRequestMethod("POST");
break;
case PUT:
conn.setRequestMethod("PUT");
break;
case DELETE:
conn.setRequestMethod("DELETE");
break;
}
conn.setDoInput(true);
conn.setDoOutput(m != DownZ.Method.GET);
//write headers if any
if (headers.size() > 0) {
for (HeaderParams header : headers) {
conn.setRequestProperty(header.getKey(), header.getValue());
}
}
Uri.Builder builder = new Uri.Builder();
//write request parameters
if (params.size() > 0) {
for (RequestParams itm : params) {
builder.appendQueryParameter(itm.getKey(), itm.getValue());
}
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
}
conn.connect();
int response = conn.getResponseCode();
is = conn.getInputStream();
Response resp = new Response();
resp.setCode(response);
resp.setData(is);
return resp;
}
示例6: post
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public Response post(String uri, Map<String, Object> headers, Map<String, Object> params) {
// POST request with parameter map
String requestAddress = NetworkingHelper.createRequestAddress(this.targetAddress, uri);
// Request address with uri
try {
url = new URL(requestAddress);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
// Enable do output
connection.setReadTimeout(this.readTimeout);
connection.setConnectTimeout(this.connectTimeout);
if(headers != null && headers.size() > 0) {
for(String key : headers.keySet()) {
connection.setRequestProperty(key, (String) headers.get(key));
}
}
if(params != null && params.size() > 0) {
OutputStream out = connection.getOutputStream();
out.write(NetworkingHelper.createParamBytes(params));
// Send byte[] data if body data is exists
out.flush();
}
return NetworkingHelper.getResponse(connection);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
示例7: openConnection
import java.net.HttpURLConnection; //导入方法依赖的package包/类
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);
if (b.a.equals(url.getProtocol()) && this.mSslSocketFactory != null) {
((HttpsURLConnection) connection).setSSLSocketFactory(this.mSslSocketFactory);
}
return connection;
}
示例8: openConnection
import java.net.HttpURLConnection; //导入方法依赖的package包/类
@NonNull
private HttpURLConnection openConnection(Uri path) throws IOException {
final HttpURLConnection connection = (HttpURLConnection) new URL(path.toString()).openConnection();
connection.setConnectTimeout(BittrexApiClient.DEFAULT_CONNECT_TIMEOUT_MILLIS);
connection.setReadTimeout(BittrexApiClient.DEFAULT_READ_TIMEOUT_MILLIS);
return connection;
}
示例9: openConnection
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Opens an {@link HttpURLConnection} with parameters.
*
* @param request
* @param listener
* @return an open connection
* @throws IOException
*/
private HttpURLConnection openConnection(WXRequest request, OnHttpListener listener) throws IOException {
URL url = new URL(request.url);
HttpURLConnection connection = createConnection(url);
connection.setConnectTimeout(request.timeoutMs);
connection.setReadTimeout(request.timeoutMs);
connection.setUseCaches(false);
connection.setDoInput(true);
if (request.paramMap != null) {
Set<String> keySets = request.paramMap.keySet();
for (String key : keySets) {
connection.addRequestProperty(key, request.paramMap.get(key));
}
}
if ("POST".equals(request.method) || "PUT".equals(request.method) || "PATCH".equals(request.method)) {
connection.setRequestMethod(request.method);
if (request.body != null) {
if (listener != null) {
listener.onHttpUploadProgress(0);
}
connection.setDoOutput(true);
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
//TODO big stream will cause OOM; Progress callback is meaningless
out.write(request.body.getBytes());
out.close();
if (listener != null) {
listener.onHttpUploadProgress(100);
}
}
} else if (!TextUtils.isEmpty(request.method)) {
connection.setRequestMethod(request.method);
} else {
connection.setRequestMethod("GET");
}
return connection;
}
示例10: post
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public Response post(String uri, Map<String, Object> headers, JSONObject requestObject) {
// POST request with JSON data
String requestAddress = NetworkingHelper.createRequestAddress(this.targetAddress, uri);
// Request address with uri
try {
url = new URL(requestAddress);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
// Enable do output
connection.setReadTimeout(this.readTimeout);
connection.setConnectTimeout(this.connectTimeout);
if(headers != null && headers.size() > 0) {
for(String key : headers.keySet()) {
connection.setRequestProperty(key, (String) headers.get(key));
}
}
wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(requestObject.toString());
wr.flush();
return NetworkingHelper.getResponse(connection);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
示例11: get
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* 鍙戦�丟et璇锋眰
* @param url
* @return
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws KeyManagementException
*/
public static String get(String url) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
if(enableSSL){
return get(url,true);
}else{
StringBuffer bufferRes = null;
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
// 杩炴帴瓒呮椂
http.setConnectTimeout(25000);
// 璇诲彇瓒呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂�
http.setReadTimeout(25000);
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (http != null) {
// 鍏抽棴杩炴帴
http.disconnect();
}
return bufferRes.toString();
}
}
示例12: urlRequest
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* @param url 请求URL
* @param method 请求URL
* @param param json参数(post|put)
* @param auth 认证(username+:+password)
* @return 返回结果
*/
public static String urlRequest(String url,String method,String param,String auth){
String result = null;
try {
HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
connection.setConnectTimeout(60*1000);
connection.setRequestMethod(method.toUpperCase());
if(auth!=null&&!"".equals(auth)){
String authorization = "Basic "+new String(Base64.encodeBase64(auth.getBytes()));
connection.setRequestProperty("Authorization", authorization);
}
if(param!=null&&!"".equals(param)){
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
dos.write(param.getBytes(Consts.UTF_8));
dos.flush();
dos.close();
}else{
connection.connect();
}
if(connection.getResponseCode()==HttpURLConnection.HTTP_OK||connection.getResponseCode()==HttpURLConnection.HTTP_CREATED){
InputStream in = connection.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len = 0;
while((len=in.read(buff, 0, buff.length))>0){
out.write(buff, 0, len);
}
byte[] data = out.toByteArray();
in.close();
result = data!=null&&data.length>0?new String(data, Consts.UTF_8):null;
}else{
result = "{\"status\":"+connection.getResponseCode()+",\"msg\":\""+connection.getResponseMessage()+"\"}";
}
connection.disconnect();
}catch (Exception e) {
logger.error("--http request error !",e);
}
return result;
}
示例13: getImageStream
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public static InputStream getImageStream(String path) throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return conn.getInputStream();
}
return null;
}
示例14: urlRequest
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* @param url 请求URL
* @param method 请求URL
* @param param json参数(post|put)
* @return
*/
public static String urlRequest(String url,String method,String param,String auth){
String result = null;
try {
HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
connection.setConnectTimeout(60*1000);
connection.setRequestMethod(method.toUpperCase());
if(auth!=null&&!"".equals(auth)){
String authorization = "Basic "+new String(Base64.encodeBase64(auth.getBytes()));
connection.setRequestProperty("Authorization", authorization);
}
if(param!=null&&!"".equals(param)){
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
dos.write(param.getBytes(Consts.UTF_8));
dos.flush();
dos.close();
}else{
connection.connect();
}
if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
InputStream in = connection.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len = 0;
while((len=in.read(buff, 0, buff.length))>0){
out.write(buff, 0, len);
}
byte[] data = out.toByteArray();
in.close();
result = data!=null&&data.length>0?new String(data, Consts.UTF_8):null;
}else{
result = "{\"status\":"+connection.getResponseCode()+",\"msg\":\""+connection.getResponseMessage()+"\"}";
}
connection.disconnect();
}catch (Exception e) {
logger.error("--http request error !",e);
}
return result;
}
示例15: get
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* 鍙戦�丟et璇锋眰
*
* @param url
* @return
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws KeyManagementException
*/
public static String get(String url) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException{
if (enableSSL) {
return get(url, true);
} else {
StringBuffer bufferRes = null;
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
// 杩炴帴瓒呮椂
http.setConnectTimeout(25000);
// 璇诲彇瓒呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂�
http.setReadTimeout(25000);
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null) {
bufferRes.append(valueString);
}
in.close();
if (http != null) {
// 鍏抽棴杩炴帴
http.disconnect();
}
return bufferRes.toString();
}
}