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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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) {
            }
        }
    }
 
Example 41
Project: JuniperBotJ   File: BlurImageController.java   Source Code and License 5 votes vote down vote up
private ImageInfo renderImage(String sourceUrl) throws MalformedURLException, IOException {
    URL url = new URL(sourceUrl);
    URLConnection con = url.openConnection();
    con.setRequestProperty("User-Agent", USER_AGENT);

    try (InputStream input = con.getInputStream()) {
        BufferedImage image = ImageIO.read(input);
        image = scaleImage(image, BufferedImage.TYPE_INT_RGB, 1920, 1920);
        BufferedImage blurredImage = null;
        if (useOpenCV && openCVService.isInitialized()) {
            try {
                blurredImage = openCVService.blur(image, blurRadius);
            } catch (IOException e) {
                // fall down and apply legacy box blur
            }
        }
        if (blurredImage == null) {
            blurredImage = blurFilter.filter(image, null);
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(blurredImage, "jpg", out);

        ImageInfo info = new ImageInfo();
        info.inputStream = new ByteArrayInputStream(out.toByteArray());
        info.contentLength = out.size();
        return info;
    }
}
 
Example 42
Project: incubator-netbeans   File: NbURLStreamHandlerFactoryTest.java   Source Code and License 5 votes vote down vote up
private static String suck(URL u) throws Exception {
    URLConnection conn = u.openConnection();
    InputStream is = conn.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    FileUtil.copy(is, baos);
    is.close();
    return baos.toString("UTF-8");
}
 
Example 43
Project: openjdk-jdk10   File: NTLMAuthWithSM.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // security manager is required
    if (System.getSecurityManager() == null) {
        throw new RuntimeException("Security manager not specified");
    }

    if (System.getProperty("os.name").startsWith("Windows")) {
        // disable transparent NTLM authentication on Windows
        NTLMAuthenticationCallback.setNTLMAuthenticationCallback(
                new NTLMAuthenticationCallbackImpl());
    }

    try (LocalHttpServer server = LocalHttpServer.startServer()) {
        // set authenticator
        Authenticator.setDefault(new AuthenticatorImpl());

        String url = String.format("http://localhost:%d/test/",
                server.getPort());

        // load a document which is protected with NTML authentication
        System.out.println("load() called: " + url);
        URLConnection conn = new URL(url).openConnection();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(conn.getInputStream()))) {

            String line = reader.readLine();
            if (line == null) {
                throw new IOException("Couldn't read a response");
            }
            do {
                System.out.println(line);
            } while ((line = reader.readLine()) != null);
        }
    }

    System.out.println("Test passed");
}
 
Example 44
Project: openjdk-jdk10   File: plain.java   Source Code and License 5 votes vote down vote up
/**
 * Returns one of several object types (this set may change in future
 * versions):
 * 1) instance of Thread:
 *    Invoke the thread to launch an external viewer.
 * 2) instance of InputStream:
 *    Bring up the "Save to disk" dialog page to allow the content
 *    to be saved to disk.
 * 3) instance of InputStreamImageSource:
 *    Load the image into HotJava in an image viewer page.
 * 4) instance of String:
 *    Go to a new page with the string as the plain text content
 *    of that page.
 */
public Object getContent(URLConnection uc) {
    try {
        InputStream is = uc.getInputStream();
        StringBuffer sb = new StringBuffer();
        int c;

        sb.append("[Content of " + uc.getURL() + "]\n\n");
        sb.append("[This opening message brought to you by your plain/text\n");
        sb.append("content handler. To remove this content handler, delete the\n");
        sb.append("COM.foo.content.text directory from your class path and\n");
        sb.append("the java.content.handler.pkgs property from your HotJava\n");
        sb.append("properties file.]\n");
        sb.append("----------------------------------------------------------------\n\n");

        // Read the characters from the source, accumulate them into the string buffer.
        // (Not the most efficient, but simplest for this example.)
        while ((c = is.read()) >= 0) {
            sb.append((char)c);
        }

        // Tidy up
        is.close();

        // Return the resulting string to our client (we're case 4 above)
        return sb.toString();
    } catch (IOException e) {
        // For any exception, just return an indication of what went wrong.
        return "Problem reading document: " + uc.getURL();
    }
}
 
Example 45
Project: uppercore   File: DownloadableUpdateChecker.java   Source Code and License 5 votes vote down vote up
public void tryToDownload(URLConnection connection, File file, Consumer<IOException> exceptionHandler, CommandSender caller){
    DownloadSession session;
    try {
        session = new DownloadSession(connection, file);
    } catch (IOException e) {
        exceptionHandler.accept(e);
        return;
    }
    DownloadNotifier notifier = downloadNotifierConstructor.create(session, caller);
    notifier.setLogger(getLogger());
    session.startAsync(() -> {
        notifier.stop();
        onUpdateEnd(file, caller);
    });
}
 
Example 46
Project: TFG-SmartU-La-red-social   File: MultipartUtility.java   Source Code and License 5 votes vote down vote up
/**
 * Adds a upload file section to the request
 * @param fieldName name attribute in <input type="file" name="..." />
 * @param uploadFile a File to be uploaded
 * @throws IOException
 */
public void addFilePart(String fieldName, File uploadFile)
        throws IOException {
    String fileName = uploadFile.getName();
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append(
            "Content-Disposition: form-data; name=\"" + fieldName
                    + "\"; filename=\"" + fileName + "\"")
            .append(LINE_FEED);
    writer.append(
            "Content-Type: "
                    + URLConnection.guessContentTypeFromName(fileName))
            .append(LINE_FEED);
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.flush();

    FileInputStream inputStream = new FileInputStream(uploadFile);
    byte[] buffer = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }
    outputStream.flush();
    inputStream.close();

    writer.append(LINE_FEED);
    writer.flush();
}
 
Example 47
Project: Capatchafy   File: CapatchaPage.java   Source Code and License 5 votes vote down vote up
public boolean validateCaptcha(String secret, String response, String remoteip)
{
    JsonObject jsonObject = null;
    URLConnection connection = null;
    InputStream is = null;
    String charset = java.nio.charset.StandardCharsets.UTF_8.name();

    String url = "https://www.google.com/recaptcha/api/siteverify";
    try 
    {
        String query = String.format("secret=%s&response=%s&remoteip=%s",
                URLEncoder.encode(secret, charset),
                URLEncoder.encode(response, charset),
                URLEncoder.encode(remoteip, charset));

        connection = new URL(url + "?" + query).openConnection();
        is = connection.getInputStream();
        JsonReader rdr = Json.createReader(is);
        jsonObject = rdr.readObject();
    } 
    catch (IOException ex) 
    {
        Bukkit.broadcastMessage(ex.getStackTrace().toString());
    }
    finally 
    {
        if (is != null) 
        {
            try 
            {
                is.close();
            } 
            catch (IOException e)
            {
                System.out.print(e.getLocalizedMessage());
            }
        }
    }
    return jsonObject.getBoolean("success");
}
 
Example 48
Project: aws-photosharing-example   File: ContentFacadeTest.java   Source Code and License 5 votes vote down vote up
private void uploadDataToBucket() throws IOException {

        URL url = this.getClass().getResource("../../../../amazon-aws-logo.jpg");
        String tmpFileName = url.getFile();

        File file = new File(tmpFileName);
        String fileName = file.getName();
        InputStream is = url.openStream();
        String contentType = URLConnection.guessContentTypeFromStream(is);

        User userJohn = new User();
        userJohn.setEmail("[email protected]");
        userJohn.setUserName("jondoe");
        userJohn.updatePassword("mypassword");

        User _sharedUser = new User();
        _sharedUser.setEmail("[email protected]");
        _sharedUser.setUserName("aliceN");
        _sharedUser.updatePassword("mypwd");

        _user = userFacade.register(userJohn);
        sharedUser = userFacade.register(_sharedUser);

        Comment comment = new Comment();
        comment.setText("My comment");
        Set<Comment> comments = new HashSet<>();
        comments.add(comment);

        uploadedMedia = contentFacade.uploadPictureToS3(_user, fileName, is, contentType, comment);
    }
 
Example 49
Project: GitHub   File: ResponseCacheTest.java   Source Code and License 5 votes vote down vote up
@Test public void requestPragmaNoCache() throws Exception {
  server.enqueue(new MockResponse()
      .addHeader("Last-Modified: " + formatDate(-120, TimeUnit.SECONDS))
      .addHeader("Date: " + formatDate(0, TimeUnit.SECONDS))
      .addHeader("Cache-Control: max-age=60")
      .setBody("A"));
  server.enqueue(new MockResponse().setBody("B"));

  URL url = server.url("/").url();
  assertEquals("A", readAscii(openConnection(url)));
  URLConnection connection = openConnection(url);
  connection.setRequestProperty("Pragma", "no-cache");
  assertEquals("B", readAscii(connection));
}
 
Example 50
Project: lams   File: HttpWebResponse.java   Source Code and License 5 votes vote down vote up
private void readHeaders( URLConnection connection ) throws IOException {
    loadHeaders( connection );
    if (connection instanceof HttpURLConnection) {
        readResponseHeader( (HttpURLConnection) connection );
    } else {
        _responseCode = HttpURLConnection.HTTP_OK;
        _responseMessage = "OK";
        if (connection.getContentType().startsWith( "text" )) {
            setContentTypeHeader( connection.getContentType() + "; charset=" + FILE_ENCODING );
        }
    }
}
 
Example 51
Project: incubator-netbeans   File: XmlFileEncodingQueryImplTest.java   Source Code and License 5 votes vote down vote up
private void performTest (final URLConnection template) throws IOException {
    final File test = new File(getWorkDir(), getName() +".orig");      //NOI18N
    copyToWorkDir(template, test);
    final FileObject from = FileUtil.toFileObject(test);
    assertNotNull(from);
    final FileObject to = from.getParent().createData(getName(),"res");    //NOI18N
    assertNotNull(to);
    copyFile (from, to);
    assertEquals (from, to);
}
 
Example 52
Project: siiMobilityAppKit   File: FileTransfer.java   Source Code and License 5 votes vote down vote up
private static TrackingInputStream getInputStream(URLConnection conn) throws IOException {
    String encoding = conn.getContentEncoding();
    if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
      return new TrackingGZIPInputStream(new ExposedGZIPInputStream(conn.getInputStream()));
    }
    return new SimpleTrackingInputStream(conn.getInputStream());
}
 
Example 53
Project: osc-core   File: JarURLConnector.java   Source Code and License 5 votes vote down vote up
@Override
public TaggedData connectTagged(URL url) throws Exception {
	URLConnection connection = url.openConnection();
	if (connection instanceof JarURLConnection) {
           connection.setUseCaches(false);
       }
	return new TaggedData(connection, connection.getInputStream());
}
 
Example 54
Project: OpenJSharp   File: JarFileFactory.java   Source Code and License 5 votes vote down vote up
URLConnection getConnection(JarFile jarFile) throws IOException {
    URL u;
    synchronized (instance) {
        u = urlCache.get(jarFile);
    }
    if (u != null)
        return u.openConnection();

    return null;
}
 
Example 55
Project: lams   File: UpdateChecker.java   Source Code and License 5 votes vote down vote up
private Properties getUpdateProperties(URL updateUrl) throws IOException {
  URLConnection connection = updateUrl.openConnection();
  connection.setConnectTimeout(3 * 1000);
  InputStream in = connection.getInputStream();
  try {
    Properties props = new Properties();
    props.load(connection.getInputStream());
    return props;
  } finally {
    if (in != null) {
      in.close();
    }
  }
}
 
Example 56
Project: Snow-Globe   File: UpstreamUtil.java   Source Code and License 5 votes vote down vote up
private static boolean upstreamRunning() {
    try {
        URL url = new URL("http://localhost:" + UPSTREAM_SERVICE_PORT + "/health");
        URLConnection uc = url.openConnection();
        uc.connect();
        String status = uc.getHeaderField(0);
        return status.contains("200");

    } catch (Exception e) {
        return false;
    }
}
 
Example 57
Project: invest-stash-rest   File: HttpRequests.java   Source Code and License 5 votes vote down vote up
public void setConnectionParameters(URLConnection connection,
    HttpRequestMethod requestMethod) throws ProtocolException {
connection.setRequestProperty("User-Agent", USER_AGENT);
connection.setRequestProperty("Content-Type", JSON_MEDIA_TYPE);
connection.setRequestProperty("Accept", JSON_MEDIA_TYPE);
if (requestMethod.equals(HttpRequestMethod.POST)) {
    connection.setDoOutput(true);
}
   }
 
Example 58
Project: Parabot-317-API-Minified-OS-Scape   File: NetUtil.java   Source Code and License 5 votes vote down vote up
public static URLConnection createURLConnection(String url) {
    try {
        final URL           address    = new URL(url);
        final URLConnection connection = address.openConnection();
        connection.addRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0");
        connection.setConnectTimeout(5000);
        connection.setRequestProperty("Content-Type", "image/png");
        return connection;
    } catch (IOException ex) {
        System.out.println("Error creating connection!");
        ex.printStackTrace();
    }
    return null;
}
 
Example 59
Project: incubator-netbeans   File: MavenProtocolHandler.java   Source Code and License 5 votes vote down vote up
protected @Override URLConnection openConnection(URL u) throws IOException {
    String path = u.getPath();
    if (!path.startsWith("/")) {
        throw new IOException(path);
    }
    String stuff = path.substring(1);
    MavenEmbedder online = EmbedderFactory.getOnlineEmbedder();
    Artifact a;
    String[] pieces = stuff.split(":");
    if (pieces.length == 4) {
        a = online.createArtifact(pieces[0], pieces[1], pieces[2], pieces[3]);
    } else if (pieces.length == 5) {
        a = online.createArtifactWithClassifier(pieces[0], pieces[1], pieces[2], pieces[3], pieces[4]);
    } else {
        throw new IOException(stuff);
    }
    try {
        online.resolve(a, Collections.<ArtifactRepository>singletonList(online.createRemoteRepository(RepositorySystem.DEFAULT_REMOTE_REPO_URL, RepositorySystem.DEFAULT_REMOTE_REPO_ID)), online.getLocalRepository());
    } catch (Exception x) {
        throw new IOException(stuff + ": " + x, x);
    }
    File f = a.getFile();
    if (!f.isFile()) {
        throw new IOException("failed to download " + stuff);
    }
    Logger.getLogger(MavenProtocolHandler.class.getName()).log(Level.FINE, "resolved {0} -> {1}", new Object[] {stuff, f});
    return BaseUtilities.toURI(f).toURL().openConnection();
}
 
Example 60
Project: GitHub   File: URLConnectionTest.java   Source Code and License 5 votes vote down vote up
@Test public void missingChunkBody() throws IOException {
  server.enqueue(new MockResponse().setBody("5")
      .clearHeaders()
      .addHeader("Transfer-encoding: chunked")
      .setSocketPolicy(DISCONNECT_AT_END));

  URLConnection connection = urlFactory.open(server.url("/").url());
  try {
    readAscii(connection.getInputStream(), Integer.MAX_VALUE);
    fail();
  } catch (IOException e) {
  } finally {
    connection.getInputStream().close();
  }
}