本文整理汇总了Java中java.net.HttpURLConnection.disconnect方法的典型用法代码示例。如果您正苦于以下问题:Java HttpURLConnection.disconnect方法的具体用法?Java HttpURLConnection.disconnect怎么用?Java HttpURLConnection.disconnect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.net.HttpURLConnection
的用法示例。
在下文中一共展示了HttpURLConnection.disconnect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: checkRequestCaching
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Helper method to make a request with cache enabled or disabled, and check
* whether the request is successful.
* @param requestUrl request url.
* @param cacheSetting indicates cache should be used.
* @param outcome indicates request is expected to be successful.
*/
private void checkRequestCaching(String requestUrl,
CacheSetting cacheSetting,
ExpectedOutcome outcome) throws Exception {
URL url = new URL(requestUrl);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setUseCaches(cacheSetting == CacheSetting.USE_CACHE);
if (outcome == ExpectedOutcome.SUCCESS) {
assertEquals(200, connection.getResponseCode());
assertEquals("this is a cacheable file\n", TestUtil.getResponseAsString(connection));
} else {
try {
connection.getResponseCode();
fail();
} catch (IOException e) {
// Expected.
}
}
connection.disconnect();
}
示例2: isTokenInProxy
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private boolean isTokenInProxy(String token) {
try {
URL authUrl = new URL(oAuthUrl);
HttpURLConnection connection = (HttpURLConnection) authUrl.openConnection();
connection.addRequestProperty("Cookie", "_oauth2_proxy=" + token);
connection.connect();
int resonseCode = connection.getResponseCode();
connection.disconnect();
logger.debug("Successfully checked token with oauth proxy, result {}", resonseCode);
return resonseCode == HttpStatus.ACCEPTED.value();
} catch (IOException e) {
logger.error("Failed to check session token at oauth Proxy");
return false;
}
}
示例3: downloadViaHttp
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private static CharSequence downloadViaHttp(String uri, String contentTypes, int maxChars) throws IOException {
int redirects = 0;
while (redirects < 5) {
URL url = new URL(uri);
HttpURLConnection connection = safelyOpenConnection(url);
connection.setInstanceFollowRedirects(true); // Won't work HTTP -> HTTPS or vice versa
connection.setRequestProperty("Accept", contentTypes);
connection.setRequestProperty("Accept-Charset", "utf-8,*");
connection.setRequestProperty("User-Agent", "ZXing (Android)");
try {
int responseCode = safelyConnect(connection);
switch (responseCode) {
case HttpURLConnection.HTTP_OK:
return consume(connection, maxChars);
case HttpURLConnection.HTTP_MOVED_TEMP:
String location = connection.getHeaderField("Location");
if (location != null) {
uri = location;
redirects++;
continue;
}
throw new IOException("No Location");
default:
throw new IOException("Bad HTTP response: " + responseCode);
}
} finally {
connection.disconnect();
}
}
throw new IOException("Too many redirects");
}
示例4: checkupdate
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private void checkupdate() {
if (getConfig().getBoolean("check-update")) {
try {
HttpURLConnection con = (HttpURLConnection) (new URL("http://www.spigotmc.org/api/general.php")).openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.getOutputStream().write("key=98BE0FE67F88AB82B4C197FAF1DC3B69206EFDCC4D3B80FC83A00037510B99B4&resource=50530".getBytes("UTF-8"));
String version = (new BufferedReader(new InputStreamReader(con.getInputStream()))).readLine();
con.disconnect();
if (!version.equals(getDescription().getVersion())) {
getLogger().warning("There is an update available for SafeBAC. Please use the latest version at all times.");
getLogger().warning("Your version: " + getDescription().getVersion() + " | " + "New version: " + version);
getLogger().warning("Download it here: https://www.spigotmc.org/resources/sbac-safebungeeadminchat.50530/");
}
} catch (Exception ignored) {
}
}
}
示例5: testConnectBeforeWrite
import java.net.HttpURLConnection; //导入方法依赖的package包/类
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testConnectBeforeWrite() throws Exception {
URL url = new URL(NativeTestServer.getEchoBodyURL());
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setFixedLengthStreamingMode(TestUtil.UPLOAD_DATA.length);
OutputStream out = connection.getOutputStream();
connection.connect();
out.write(TestUtil.UPLOAD_DATA);
assertEquals(200, connection.getResponseCode());
assertEquals("OK", connection.getResponseMessage());
assertEquals(TestUtil.UPLOAD_DATA_STRING, TestUtil.getResponseAsString(connection));
connection.disconnect();
}
示例6: getResponseFromHttpUrl
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* This method returns the entire result from the HTTP response.
*
* @param url The URL to fetch the HTTP response from.
* @return The contents of the HTTP response, null if no response
* @throws IOException Related to network and stream reading
*/
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
String response = null;
if (hasInput) {
response = scanner.next();
}
scanner.close();
return response;
} finally {
urlConnection.disconnect();
}
}
示例7: setTimes
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* <b>SETTIMES</b>
*
* curl -i -X PUT "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=SETTIMES
* [&modificationtime=<TIME>][&accesstime=<TIME>]"
*
* @param path
* @return
* @throws AuthenticationException
* @throws IOException
* @throws MalformedURLException
*/
public String setTimes(String path) throws MalformedURLException,
IOException, AuthenticationException {
String resp = null;
ensureValidToken();
HttpURLConnection conn = authenticatedURL.openConnection(
new URL(new URL(httpfsUrl),
MessageFormat.format("/webhdfs/v1/{0}?op=SETTIMES",
URLUtil.encodePath(path))), token);
conn.setRequestMethod("PUT");
conn.connect();
resp = result(conn, true);
conn.disconnect();
return resp;
}
示例8: post
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Send POST request
*/
public static String post(String url, Map<String, String> queryParas, String data, Map<String, String> headers) {
HttpURLConnection conn = null;
try {
conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), POST, headers);
conn.connect();
OutputStream out = conn.getOutputStream();
out.write(data != null ? data.getBytes(CHARSET) : null);
out.flush();
out.close();
return readResponseString(conn);
}
catch (Exception e) {
throw new RuntimeException(e);
}
finally {
if (conn != null) {
conn.disconnect();
}
}
}
示例9: downloadViaHttp
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private static CharSequence downloadViaHttp(String uri, String contentTypes, int maxChars) throws IOException {
int redirects = 0;
while (redirects < 5) {
URL url = new URL(uri);
HttpURLConnection connection = safelyOpenConnection(url);
connection.setInstanceFollowRedirects(true); // Won't work HTTP -> HTTPS or vice versa
connection.setRequestProperty("Accept", contentTypes);
connection.setRequestProperty("Accept-Charset", "utf-8,*");
connection.setRequestProperty("User-Agent", "ZXing (Android)");
try {
int responseCode = safelyConnect(connection);
switch (responseCode) {
case HttpURLConnection.HTTP_OK:
return consume(connection, maxChars);
case HttpURLConnection.HTTP_MOVED_TEMP:
String location = connection.getHeaderField("Location");
if (location != null) {
uri = location;
redirects++;
continue;
}
throw new IOException("No Location");
default:
throw new IOException("Bad HTTP response: " + responseCode);
}
} finally {
connection.disconnect();
}
}
throw new IOException("Too many redirects");
}
示例10: loadMappings
import java.net.HttpURLConnection; //导入方法依赖的package包/类
protected final void loadMappings() {
try {
log.info("Load Namespace Prefix Mappings form {}",GET_ALL);
HttpURLConnection con = (HttpURLConnection)GET_ALL.openConnection();
con.setReadTimeout(5000); //set the max connect & read timeout to 5sec
con.setConnectTimeout(5000);
con.connect();
String contentType = con.getContentType().split(";")[0];
if("text/plain".equalsIgnoreCase(contentType)){
InputStream in = con.getInputStream();
try {
cache = new NamespacePrefixProviderImpl(in);
cacheStamp = System.currentTimeMillis();
log.info(" ... completed");
} finally {
IOUtils.closeQuietly(in);
}
} else {
log.warn("Response from prefix.cc does have the wrong content type '"
+ contentType + "' (expected: text/plain). This indicates that the "
+ "service is currently unavailable!");
}
con.disconnect(); //we connect once every {long-period}
} catch (IOException e) {
log.warn("Unable to load prefix.cc NamespaceMappings (Message: "
+ e.getMessage() +")",e);
;
}
}
示例11: getBitmap
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
Bitmap b = decodeFile(f);
if(b!=null)
return b;
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex){
ex.printStackTrace();
if(ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
示例12: post
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public static HttpResponseEntity post(String requestUri, HttpRequestEntity requestEntity) {
HttpURLConnection conn = null;
OutputStream out = null;
String contextType = null;
HttpResponseEntity rsp = null;
try {
if (requestEntity.getFileParams().isEmpty()) {
contextType = "application/x-www-form-urlencoded;charset=" + requestEntity.getCharset();
conn = getConnection(new URL(requestUri), METHOD_POST, contextType, requestEntity);
out = conn.getOutputStream();
String query = buildQuery(requestEntity.getTextParams(), requestEntity.getCharset());
byte[] content = {};
if (query != null) {
content = query.getBytes(requestEntity.getCharset());
}
conn.setRequestProperty("Content-Length", String.valueOf(content.length));
out.write(content);
} else {
String boundary = String.valueOf(System.nanoTime()); // 随机分隔线
contextType = "multipart/form-data;charset=" + requestEntity.getCharset() + ";boundary=" + boundary;
conn = getConnection(new URL(requestUri), METHOD_POST, contextType, requestEntity);
out = conn.getOutputStream();
byte[] entryBoundaryBytes = ("\r\n--" + boundary + "\r\n").getBytes(requestEntity.getCharset());
// 组装文本请求参数
Set<Entry<String, String>> textEntrySet = requestEntity.getTextParams().entrySet();
for (Entry<String, String> textEntry : textEntrySet) {
byte[] textBytes = getTextEntry(textEntry.getKey(), textEntry.getValue(), requestEntity.getCharset());
out.write(entryBoundaryBytes);
out.write(textBytes);
}
// 组装文件请求参数
Set<Entry<String, FileItem>> fileEntrySet = requestEntity.getFileParams().entrySet();
for (Entry<String, FileItem> fileEntry : fileEntrySet) {
FileItem fileItem = fileEntry.getValue();
if (fileItem.getContent() == null) {
continue;
}
byte[] fileBytes = getFileEntry(fileEntry.getKey(), fileItem.getFileName(), fileItem.getMimeType(),
requestEntity.getCharset());
out.write(entryBoundaryBytes);
out.write(fileBytes);
out.write(fileItem.getContent());
}
// 添加请求结束标志
byte[] endBoundaryBytes = ("\r\n--" + boundary + "--\r\n").getBytes(requestEntity.getCharset());
out.write(endBoundaryBytes);
}
rsp = getResponseAsResponseEntity(conn);
} catch (Exception e) {
rsp = new HttpResponseEntity(400, e);
} finally {
if (out != null) {
try {out.close();} catch (Exception e2) {}
}
if (conn != null) {
conn.disconnect();
}
}
return rsp;
}
示例13: downloadFile
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public static void downloadFile(String sourceURL,String fileNameWithPath) throws IOException{
final int BUFFER_SIZE = 4096;
URL url = new URL(sourceURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
int index = disposition.indexOf("file=");
if (index > 0)
fileName = disposition.substring(index + 10,disposition.length() - 1);
} else {
fileName = sourceURL.substring(sourceURL.lastIndexOf("/") + 1,sourceURL.length());
}
InputStream inputStream = httpConn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(fileNameWithPath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
}
httpConn.disconnect();
}
示例14: 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();
}
}
示例15: testResolveByCoordinate
import java.net.HttpURLConnection; //导入方法依赖的package包/类
@Test
public void testResolveByCoordinate() throws Exception {
final List<URL> resolve = maven_dependency_resolver.resolveAsRemoteURLs(new DefaultArtifact("uk.ac.standrews.cs.sample_applications:hello_world_64m:1.0"));
for (URL url : resolve) {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
connection.setRequestMethod("HEAD");
assertEquals(200, connection.getResponseCode());
}
finally {
connection.disconnect();
}
}
}