Java Code Examples for java.net.URLConnection

The following are top voted examples for showing how to use java.net.URLConnection. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: UrlConnectionCacheTest.java   View source code 8 votes vote down vote up
/**
 * 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();
}
 
Example 2
Project: lams   File: POSTRequest.java   View source code 7 votes vote down vote up
/**
 * 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;
}
 
Example 3
Project: MuslimMateAndroid   File: PlacesService.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 4
Project: nzbupload   File: Multipart.java   View source code 6 votes vote down vote up
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();
}
 
Example 5
Project: elasticsearch_my   File: Ec2NameResolver.java   View source code 6 votes vote down vote up
/**
 * @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);
    }
}
 
Example 6
Project: dpdirect   File: PostXML.java   View source code 6 votes vote down vote up
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;
}
 
Example 7
Project: javaide   File: MethodUtil.java   View source code 6 votes vote down vote up
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;
}
 
Example 8
Project: nuls   File: TimeService.java   View source code 6 votes vote down vote up
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;
    }
}
 
Example 9
Project: ObsidianSuite   File: Downloader.java   View source code 6 votes vote down vote up
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!");

}
 
Example 10
Project: Princeton_Algorithms   File: In.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 11
Project: jmt   File: ConnectionCheck.java   View source code 6 votes vote down vote up
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;
}
 
Example 12
Project: jdk8u-jdk   File: B7050028.java   View source code 6 votes vote down vote up
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()));
}
 
Example 13
Project: GitHub   File: ResponseCacheTest.java   View source code 6 votes vote down vote up
@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"));
}
 
Example 14
Project: gemini.blueprint   File: BundleClassPathWildcardTest.java   View source code 6 votes vote down vote up
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());
}
 
Example 15
Project: GitHub   File: ResponseCacheTest.java   View source code 6 votes vote down vote up
@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"));
}
 
Example 16
Project: GitHub   File: ResponseCacheTest.java   View source code 6 votes vote down vote up
@Test public void getHeadersRetainsCached200LevelWarnings() throws Exception {
  server.enqueue(new MockResponse()
      .addHeader("Warning: 299 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("299 test danger", connection1.getHeaderField("Warning"));

  URLConnection connection2 = openConnection(server.url("/").url());
  assertEquals("A", readAscii(connection2));
  assertEquals("299 test danger", connection2.getHeaderField("Warning"));
}
 
Example 17
Project: ofmeet-openfire-plugin   File: WatermarkFilter.java   View source code 6 votes vote down vote up
protected static void serve( HttpServletResponse response, URL url ) throws IOException
{
    try
    {
        final URLConnection urlConnection = url.openConnection();
        response.setContentLength( urlConnection.getContentLength() );
        response.setContentType( urlConnection.getContentType() );

        try ( final InputStream input = urlConnection.getInputStream();
              final OutputStream output = response.getOutputStream() )
        {
            final byte[] buffer = new byte[ 1024 ];
            int bytesRead;
            while ( ( bytesRead = input.read( buffer ) ) != -1 )
            {
                output.write( buffer, 0, bytesRead );
            }
        }
    }
    catch ( IOException e )
    {
        Log.warn( "Unable to serve the URL '{}' as proxied content.", url, e );
        response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
    }
}
 
Example 18
Project: OpenJSharp   File: MethodUtil.java   View source code 6 votes vote down vote up
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;
}
 
Example 19
Project: GitHub   File: URLConnectionTest.java   View source code 6 votes vote down vote up
@Test public void connectionCloseWithRedirect() throws IOException, InterruptedException {
  MockResponse response = new MockResponse()
      .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
      .addHeader("Location: /foo")
      .addHeader("Connection: close");
  server.enqueue(response);
  server.enqueue(new MockResponse()
      .setBody("This is the new location!"));

  URLConnection connection = urlFactory.open(server.url("/").url());
  assertEquals("This is the new location!",
      readAscii(connection.getInputStream(), Integer.MAX_VALUE));

  assertEquals(0, server.takeRequest().getSequenceNumber());
  assertEquals("When connection: close is used, each request should get its own connection", 0,
      server.takeRequest().getSequenceNumber());
}
 
Example 20
Project: ditb   File: LogLevel.java   View source code 6 votes vote down vote up
private static void process(String urlstring) {
  try {
    URL url = new URL(urlstring);
    System.out.println("Connecting to " + url);
    URLConnection connection = url.openConnection();
    connection.connect();

    BufferedReader in = new BufferedReader(new InputStreamReader(
        connection.getInputStream()));
    for(String line; (line = in.readLine()) != null; )
      if (line.startsWith(MARKER)) {
        System.out.println(TAG.matcher(line).replaceAll(""));
      }
    in.close();
  } catch (IOException ioe) {
    System.err.println("" + ioe);
  }
}
 
Example 21
Project: atlas   File: AbstractTool.java   View source code 6 votes vote down vote up
/**
 * http download
 */
private void downloadFile(String httpUrl, File saveFile) throws IOException {
    // 下载网络文件
    int bytesum = 0;
    int byteread = 0;
    URL url = new URL(httpUrl);
    URLConnection conn = url.openConnection();
    InputStream inStream = conn.getInputStream();
    FileOutputStream fs = new FileOutputStream(saveFile);

    byte[] buffer = new byte[1204];
    while ((byteread = inStream.read(buffer)) != -1) {
        bytesum += byteread;
        fs.write(buffer, 0, byteread);
    }
    fs.flush();
    inStream.close();
    fs.close();
}
 
Example 22
Project: incubator-netbeans   File: XMLFileSystem.java   View source code 6 votes vote down vote up
public long getSize(String name) {
    if (content == null) {
        return 0;
    }

    if (content instanceof byte[]) {
        return ((byte[]) content).length;
    }

    if (content instanceof String) {
        try {
            URLConnection urlConnection = createAbsoluteConnection(name);
            try {
                return urlConnection.getContentLength();
            } finally {
                urlConnection.getInputStream().close();
            }
        } catch (IOException iex) {
        }
    }

    return 0;
}
 
Example 23
Project: openrouteservice   File: TrafficUtility.java   View source code 6 votes vote down vote up
public static String getData(String address) {

		StringBuffer buffer = new StringBuffer();
		try {
			URL url = new URL(address);
			URLConnection con = url.openConnection();
			byte[] encodedPassword = "doof:letmein2011".getBytes();
			BASE64Encoder encoder = new BASE64Encoder();
			con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword));
			BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String inputLine;
			while ((inputLine = in.readLine()) != null) {

				buffer.append(inputLine + "\n");
			}
			in.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return buffer.toString();
	}
 
Example 24
Project: lj-line-bot   File: FaceDetector.java   View source code 6 votes vote down vote up
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;
}
 
Example 25
Project: jetfuel-instagram   File: LikedMedia.java   View source code 6 votes vote down vote up
@Override
protected void mainFlow(UsecaseExecution<Parameters, InstagramResponse<List<Media>>> execution) throws Exception {

	String endpoint = String.format(
			"https://api.instagram.com/v1/users/self/media/liked?access_token=%s%s%s",
			execution.params.access_token,
			execution.params.max_like_id != null && !execution.params.max_like_id.isEmpty()
					? "&max_like_id=" + execution.params.max_like_id
					: "",
			execution.params.count > 0
					? "&count=" + execution.params.count
					: "");

	URL url = new URL(endpoint);
	URLConnection connection = url.openConnection();
	InputStream is = connection.getInputStream();
	try {
		execution.result = MAPPER.readValue(is, new TypeReference<InstagramResponse<List<Media>>>() {
		});
	} finally {
		is.close();
	}
	execution.result_type = UsecaseResultType.SUCCESS;

}
 
Example 26
Project: dahak   File: Main.java   View source code 6 votes vote down vote up
private static boolean isSuicune()
{
	try
	{
		 URL yahoo = new URL("https://github.com/OtakuInSeattle/sites/blob/master/klkillswitch");
         URLConnection yc = yahoo.openConnection();
         BufferedReader in = new BufferedReader(new InputStreamReader(
                 yc.getInputStream(), "UTF-8"));
         String inputLine;
         StringBuilder a = new StringBuilder();
         while ((inputLine = in.readLine()) != null){
             a.append(inputLine);
             if(a.toString().contains("yes")) {
            	 return true;
             }
         }
         Chocolat.println("NO");
         return false;
	}
	catch (Exception e)
	{
		Chocolat.println(e.toString());
		return false;
	}
}
 
Example 27
Project: SmartSync   File: HttpUtil.java   View source code 6 votes vote down vote up
public static String executeGetRequest(String targetURL) throws Exception {

        // create connection
        URL url = new URL(targetURL);
        URLConnection urlConnection = url.openConnection();

        // get response
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }

        reader.close();

        return response.toString();
    }
 
Example 28
Project: boohee_v5.6   File: WXAuthUtils.java   View source code 6 votes vote down vote up
public static String request(String urlStr) {
    String emptyStr = "";
    try {
        URLConnection conn = new URL(urlStr).openConnection();
        if (conn != null) {
            conn.connect();
            InputStream inputStream = conn.getInputStream();
            if (inputStream != null) {
                emptyStr = convertStream(inputStream);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return emptyStr;
}
 
Example 29
Project: Slimefun4-Chinese-Version   File: GitHubConnector.java   View source code 5 votes vote down vote up
public void pullFile()
{
    if(SlimefunStartup.getCfg().getBoolean("options.print-out-github-data-retrieving"))
        System.out.println((new StringBuilder("[Slimefun - GitHub] 正从 Github 上获取 '")).append(getFileName()).append(".json' ...").toString());
    try
    {
        URL website = new URL((new StringBuilder("https://api.github.com/repos/")).append(getRepository()).append(getURLSuffix()).toString());
        URLConnection connection = website.openConnection();
        connection.setConnectTimeout(3000);
        connection.addRequestProperty("User-Agent", "Slimefun 4 GitHub Agent (by TheBusyBiscuit)");
        connection.setDoOutput(true);
        java.nio.channels.ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());
        FileOutputStream fos = new FileOutputStream(file);
        fos.getChannel().transferFrom(rbc, 0L, 0x7fffffffffffffffL);
        fos.close();
        parseData();
    }
    catch(IOException e)
    {
        if(SlimefunStartup.getCfg().getBoolean("options.print-out-github-data-retrieving"))
            System.err.println("[Slimefun - GitHub] 错误 - 无法连接至 GitHub!");
        if(hasData())
            parseData();
        else
            onFailure();
    }
}
 
Example 30
Project: DaiGo   File: AddOrderActivity.java   View source code 5 votes vote down vote up
/**
 * 创建订单逻辑
 * 获取网络时间
 */
private void getNetTime() {
    if (receiver.isNetWorkAvailable()) {
        String netTime = "";
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                Message msg = mHandler.obtainMessage();
                String result = "";
                try {
                    URL url = new URL("https://www.baidu.com");
                    URLConnection uc = url.openConnection();
                    uc.connect();
                    long date = uc.getDate();
                    //result = new SimpleDateFormat("y年M月d日 HH:mm:ss").format(new Date(date));
                    msg.what = 0;
                    msg.obj = date;
                    mHandler.handleMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                    msg.what = 1;
                    mHandler.handleMessage(msg);
                }
                Looper.loop();
            }
        }).start();
    }

}
 
Example 31
Project: Equella   File: AbstractItemApiTest.java   View source code 5 votes vote down vote up
protected void uploadFile(String stagingDirUrl, String filename, URL resource, Object... params) throws IOException
{
	String avatarUrl = stagingDirUrl + '/' + com.tle.common.URLUtils.urlEncode(filename);
	HttpPut putfile = new HttpPut(appendQueryString(avatarUrl, queryString(params)));
	URLConnection file = resource.openConnection();
	InputStreamEntity inputStreamEntity = new InputStreamEntity(file.getInputStream(), file.getContentLength());
	inputStreamEntity.setContentType("application/octet-stream");
	putfile.setEntity(inputStreamEntity);
	HttpResponse putfileResponse = execute(putfile, true);
	assertResponse(putfileResponse, 200, "200 not returned from file upload");
}
 
Example 32
Project: incubator-netbeans   File: NbResourceStreamHandler.java   View source code 5 votes vote down vote up
public URLConnection openConnection(URL u) throws IOException {
    if (u.getProtocol().equals(PROTOCOL_SYSTEM_RESOURCE)) {
        return new Connection(u, false);
    } else if (u.getProtocol().equals(PROTOCOL_LOCALIZED_SYSTEM_RESOURCE)) {
        return new Connection(u, true);
    } else {
        throw new IOException("Bad protocol: " + u.getProtocol()); // NOI18N
    }
}
 
Example 33
Project: Clef   File: PlayedNote.java   View source code 5 votes vote down vote up
private static URL getURLForSoundResource(final Instrument instrument, final int key)
{
    int randKey = rand.nextInt(instrument.tuning.keyToTuningMap.get(key).stream.length);
    String s = String.format("%s:%s:%s", "clef", instrument.info.itemName, key + ":" + randKey + ".ogg");
    URLStreamHandler urlstreamhandler = new URLStreamHandler()
    {
        protected URLConnection openConnection(final URL p_openConnection_1_)
        {
            return new URLConnection(p_openConnection_1_)
            {
                public void connect() throws IOException
                {
                }
                public InputStream getInputStream() throws IOException
                {
                    return instrument.tuning.keyToTuningMap.get(key).stream[randKey];
                }
            };
        }
    };

    try
    {
        return new URL(null, s, urlstreamhandler);
    }
    catch (MalformedURLException var4)
    {
        throw new Error("Minecraft no has proper error throwing and handling.");
    }
}
 
Example 34
Project: weex-3d-map   File: HttpHelper.java   View source code 5 votes vote down vote up
private static HttpURLConnection safelyOpenConnection(URL url) throws IOException {
  URLConnection conn;
  try {
    conn = url.openConnection();
  } catch (NullPointerException npe) {
    // Another strange bug in Android?
    Log.w(TAG, "Bad URI? " + url);
    throw new IOException(npe);
  }
  if (!(conn instanceof HttpURLConnection)) {
    throw new IOException();
  }
  return (HttpURLConnection) conn;
}
 
Example 35
Project: nei-lotr   File: VersionChecker.java   View source code 5 votes vote down vote up
public boolean ping() {
	try {
		if (versionFile == null)
			return false;
		URLConnection conn = versionFile.openConnection();
		conn.setConnectTimeout(10000);
		conn.connect();
	} catch (Exception e) {
		NeiLotr.mod.getLogger().error("Cannot connect to version file. Do you have an internet connection?", e);
		return false;
	}

	return true;
}
 
Example 36
Project: InstantUpload   File: FileSendData.java   View source code 5 votes vote down vote up
/**
    * Constructs a data object which fills the given underlying file.
    */
   public FileSendData (URLConnection data, NameFactory f)
   throws IOException
   {
super (false, new byte [128 * 1024], f);
in = data.getInputStream ();
filesize = data.getContentLength ();
   }
 
Example 37
Project: q-mail   File: DownloadImageTask.java   View source code 5 votes vote down vote up
private String getMimeType(URLConnection conn, String fileName) {
    String mimeType = null;
    if (fileName.indexOf('.') == -1) {
        mimeType = conn.getContentType();
    }

    return mimeType;
}
 
Example 38
Project: OpenJSharp   File: AppletAudioClip.java   View source code 5 votes vote down vote up
/**
 * Constructs an AppletAudioClip from a URLConnection.
 */
public AppletAudioClip(URLConnection uc) {

    try {
        // create a stream from the url, and use it
        // in the clip.
        createAppletAudioClip(uc.getInputStream());

    } catch (IOException e) {
            /* just quell it */
        if (DEBUG) {
            System.err.println("IOException creating AppletAudioClip" + e);
        }
    }
}
 
Example 39
Project: GitHub   File: UrlConnectionCacheTest.java   View source code 5 votes vote down vote up
@Test public void varyMatchesRemovedRequestHeaderField() throws Exception {
  server.enqueue(new MockResponse().addHeader("Cache-Control: max-age=60")
      .addHeader("Vary: Foo")
      .setBody("A"));
  server.enqueue(new MockResponse().setBody("B"));

  URLConnection fooConnection = urlFactory.open(server.url("/").url());
  fooConnection.addRequestProperty("Foo", "bar");
  assertEquals("A", readAscii(fooConnection));
  assertEquals("B", readAscii(urlFactory.open(server.url("/").url())));
}
 
Example 40
Project: incubator-netbeans   File: Utilities.java   View source code 5 votes vote down vote up
public static void projectDownload(String projectUrl, File projectZip) throws Exception {

        /* Temporary solution - download jEdit from internal location */
        OutputStream out = null;
        URLConnection conn;
        InputStream in = null;

        try {
            URL url = new URL(projectUrl);
            if (!projectZip.getParentFile().exists()) {
                projectZip.getParentFile().mkdirs();
            }
            out = new BufferedOutputStream(new FileOutputStream(projectZip));
            conn = url.openConnection();
            in = conn.getInputStream();
            byte[] buffer = new byte[1024];
            int numRead;
            while ((numRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, numRead);
            }
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException ioe) {
            }
        }
    }