当前位置: 首页>>代码示例>>Java>>正文


Java URLConnection类代码示例

本文整理汇总了Java中java.net.URLConnection的典型用法代码示例。如果您正苦于以下问题:Java URLConnection类的具体用法?Java URLConnection怎么用?Java URLConnection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


URLConnection类属于java.net包,在下文中一共展示了URLConnection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: readAscii

import java.net.URLConnection; //导入依赖的package包/类
/**
 * Reads {@code count} characters from the stream. If the stream is exhausted before {@code count}
 * characters can be read, the remaining characters are returned and the stream is closed.
 */
private String readAscii(URLConnection connection, int count) throws IOException {
  HttpURLConnection httpConnection = (HttpURLConnection) connection;
  InputStream in = httpConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST
      ? connection.getInputStream()
      : httpConnection.getErrorStream();
  StringBuilder result = new StringBuilder();
  for (int i = 0; i < count; i++) {
    int value = in.read();
    if (value == -1) {
      in.close();
      break;
    }
    result.append((char) value);
  }
  return result.toString();
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:21,代码来源:UrlConnectionCacheTest.java

示例2: send

import java.net.URLConnection; //导入依赖的package包/类
/**
 * Sends the request and returns the response.
 * 
 * @return String
 */
public String send() throws Exception {
    URLConnection con = this.url.openConnection();
    con.setDoOutput(true);

    OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
    out.write(this.body);
    out.close();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String response = "";
    String buffer;
    while ((buffer = in.readLine()) != null) {
        response += buffer;
    }
    in.close();
    return response;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:23,代码来源:POSTRequest.java

示例3: getUrlContents

import java.net.URLConnection; //导入依赖的package包/类
/**
 * Function to send request to google places api
 *
 * @param theUrl Request url
 * @return Json response
 */
private String getUrlContents(String theUrl) {
    StringBuilder content = new StringBuilder();
    try {
        URL url = new URL(theUrl);
        URLConnection urlConnection = url.openConnection();
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(urlConnection.getInputStream()), 8);
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            content.append(line + "\n");
        }
        bufferedReader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return content.toString();
}
 
开发者ID:fekracomputers,项目名称:MuslimMateAndroid,代码行数:24,代码来源:PlacesService.java

示例4: addFile

import java.net.URLConnection; //导入依赖的package包/类
public void addFile(String name, File file)
        throws IOException {
    String fileName = file.getName();
    String mimeType = URLConnection.guessContentTypeFromName(fileName);
    println("--" + boundary);
    println("Content-Disposition: form-data; name=\"" + name
                    + "\"; filename=\"" + fileName + "\"");
    println("Content-Type: " + mimeType);
    println("Content-Transfer-Encoding: binary");
    println();
    out.flush();

    try (FileInputStream in = new FileInputStream(file)) {
        byte[] buff = new byte[4096];
        for (int n = in.read(buff); n > -1; n = in.read(buff)) {
            stream.write(buff, 0, n);
        }
    }

    println();
}
 
开发者ID:robbyn,项目名称:nzbupload,代码行数:22,代码来源:Multipart.java

示例5: 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);
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:30,代码来源:Ec2NameResolver.java

示例6: post

import java.net.URLConnection; //导入依赖的package包/类
public static String post(URLConnection connection,
                          String stringWriter,
                          Credentials credentials) throws Exception {

   connection.setDoInput(true);
   connection.setDoOutput(true);
   connection.setRequestProperty("Authorization",
                                 "Basic "
                                       + Base64.encode((credentials.getUserName() + ":" + new String(
                                             credentials.getPassword())).getBytes()));
   OutputStreamWriter postData = new OutputStreamWriter(connection.getOutputStream());
   postData.write(stringWriter);
   postData.flush();
   postData.close();

   BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
   String response = "";
   String line = "";
   while ((line = in.readLine()) != null)
      response = response + line;
   in.close();

   return response;
}
 
开发者ID:mqsysadmin,项目名称:dpdirect,代码行数:25,代码来源:PostXML.java

示例7: getBytes

import java.net.URLConnection; //导入依赖的package包/类
private static byte[] getBytes(URL url) throws IOException {
    URLConnection uc = url.openConnection();
    if (uc instanceof java.net.HttpURLConnection) {
        java.net.HttpURLConnection huc = (java.net.HttpURLConnection) uc;
        int code = huc.getResponseCode();
        if (code >= java.net.HttpURLConnection.HTTP_BAD_REQUEST) {
            throw new IOException("open HTTP connection failed.");
        }
    }
    int len = uc.getContentLength();
    InputStream in = new BufferedInputStream(uc.getInputStream());

    byte[] b;
    try {
        b = IOUtils.readFully(in, len, true);
    } finally {
        in.close();
    }
    return b;
}
 
开发者ID:tranleduy2000,项目名称:javaide,代码行数:21,代码来源:MethodUtil.java

示例8: syncWebTime

import java.net.URLConnection; //导入依赖的package包/类
private void syncWebTime() {
    try {
        long localBeforeTime = System.currentTimeMillis();
        URL url = new URL(webTimeUrl);
        URLConnection connection = url.openConnection();
        connection.connect();
        long netTime = connection.getDate();

        long localEndTime = System.currentTimeMillis();

        netTimeOffset = (netTime + (localEndTime - localBeforeTime) / 2) - localEndTime;

        lastSyncTime = localEndTime;
    } catch (IOException e) {
        // 1 minute later try again
        lastSyncTime = lastSyncTime + 60000L;
    }
}
 
开发者ID:nuls-io,项目名称:nuls,代码行数:19,代码来源:TimeService.java

示例9: downloadZip

import java.net.URLConnection; //导入依赖的package包/类
private void downloadZip(String link) throws MalformedURLException, IOException
{
	URL url = new URL(link);
	URLConnection conn = url.openConnection();
	InputStream is = conn.getInputStream();
	long max = conn.getContentLength();
	gui.setOutputText("Downloding file...");
	BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(new File("update.zip")));
	byte[] buffer = new byte[32 * 1024];
	int bytesRead = 0;
	int in = 0;
	while ((bytesRead = is.read(buffer)) != -1) {
		in += bytesRead;
		fOut.write(buffer, 0, bytesRead);
	}
	fOut.flush();
	fOut.close();
	is.close();
	gui.setOutputText("Download Complete!");

}
 
开发者ID:ObsidianSuite,项目名称:ObsidianSuite,代码行数:22,代码来源:Downloader.java

示例10: In

import java.net.URLConnection; //导入依赖的package包/类
/**
 * Initializes an input stream from a URL.
 *
 * @param  url the URL
 * @throws IllegalArgumentException if cannot open {@code url}
 * @throws IllegalArgumentException if {@code url} is {@code null}
 */
public In(URL url) {
    if (url == null) throw new IllegalArgumentException("url argument is null");
    try {
        URLConnection site = url.openConnection();
        InputStream is     = site.getInputStream();
        scanner            = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
        scanner.useLocale(LOCALE);
    }
    catch (IOException ioe) {
        throw new IllegalArgumentException("Could not open " + url, ioe);
    }
}
 
开发者ID:Lxinyuelxy,项目名称:Princeton_Algorithms,代码行数:20,代码来源:In.java

示例11: 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;
}
 
开发者ID:max6cn,项目名称:jmt,代码行数:17,代码来源:ConnectionCheck.java

示例12: main

import java.net.URLConnection; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
    URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
    int len = conn.getContentLength();
    byte[] data = new byte[len];
    InputStream is = conn.getInputStream();
    is.read(data);
    is.close();
    conn.setDefaultUseCaches(false);
    File jar = File.createTempFile("B7050028", ".jar");
    jar.deleteOnExit();
    OutputStream os = new FileOutputStream(jar);
    ZipOutputStream zos = new ZipOutputStream(os);
    ZipEntry ze = new ZipEntry("B7050028.class");
    ze.setMethod(ZipEntry.STORED);
    ze.setSize(len);
    CRC32 crc = new CRC32();
    crc.update(data);
    ze.setCrc(crc.getValue());
    zos.putNextEntry(ze);
    zos.write(data, 0, len);
    zos.closeEntry();
    zos.finish();
    zos.close();
    os.close();
    System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:27,代码来源:B7050028.java

示例13: requestMaxStaleDirectiveWithNoValue

import java.net.URLConnection; //导入依赖的package包/类
@Test public void requestMaxStaleDirectiveWithNoValue() throws IOException {
  // Add a stale response to the cache.
  server.enqueue(new MockResponse()
      .setBody("A")
      .addHeader("Cache-Control: max-age=120")
      .addHeader("Date: " + formatDate(-4, TimeUnit.MINUTES)));
  server.enqueue(new MockResponse()
      .setBody("B"));

  assertEquals("A", readAscii(openConnection(server.url("/").url())));

  // With max-stale, we'll return that stale response.
  URLConnection maxStaleConnection = openConnection(server.url("/").url());
  maxStaleConnection.setRequestProperty("Cache-Control", "max-stale");
  assertEquals("A", readAscii(maxStaleConnection));
  assertEquals("110 HttpURLConnection \"Response is stale\"",
      maxStaleConnection.getHeaderField("Warning"));
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:19,代码来源:ResponseCacheTest.java

示例14: testJarConnectionOn

import java.net.URLConnection; //导入依赖的package包/类
private void testJarConnectionOn(Resource jar) throws Exception {
	String toString = jar.getURL().toExternalForm();
	// force JarURLConnection
	String urlString = "jar:" + toString + "!/";
	URL newURL = new URL(urlString);
	System.out.println(newURL);
	System.out.println(newURL.toExternalForm());
	URLConnection con = newURL.openConnection();
	System.out.println(con);
	System.out.println(con instanceof JarURLConnection);
	JarURLConnection jarCon = (JarURLConnection) con;

	JarFile jarFile = jarCon.getJarFile();
	System.out.println(jarFile.getName());
	Enumeration enm = jarFile.entries();
	while (enm.hasMoreElements())
		System.out.println(enm.nextElement());
}
 
开发者ID:eclipse,项目名称:gemini.blueprint,代码行数:19,代码来源:BundleClassPathWildcardTest.java

示例15: getHeadersDeletesCached100LevelWarnings

import java.net.URLConnection; //导入依赖的package包/类
@Test public void getHeadersDeletesCached100LevelWarnings() throws Exception {
  server.enqueue(new MockResponse()
      .addHeader("Warning: 199 test danger")
      .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
      .addHeader("Cache-Control: max-age=0")
      .setBody("A"));
  server.enqueue(new MockResponse()
      .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED));

  URLConnection connection1 = openConnection(server.url("/").url());
  assertEquals("A", readAscii(connection1));
  assertEquals("199 test danger", connection1.getHeaderField("Warning"));

  URLConnection connection2 = openConnection(server.url("/").url());
  assertEquals("A", readAscii(connection2));
  assertEquals(null, connection2.getHeaderField("Warning"));
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:18,代码来源:ResponseCacheTest.java


注:本文中的java.net.URLConnection类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。