I wonder is it possible to write a console application that will surf to a web page without opening a browser? I want to check if a web page is alive (and check for an HTML string in it), but I don't want to open a web browser every time for this since I have a great number of web pages to check. What is the best way to go about this? I have some knowledge in java but not so much in networking with java.
any help or direction will be greatly appreciated.
You want java.net.URL.getConnection():
InputStream is = null;
try{
URL page = new URL("http://example.com/");
URLConnection connection = page.openConnection();
is = connection.getInputStream();
}
catch(MalformedURLException e)
{
// ....
}
catch(IOException e)
{
// Couldn't connect to website
}
// do something with input stream
You might give this short tutorial a try: http://download.oracle.com/javase/tutorial/networking/urls/readingURL.html
Also you will find more code samples here: http://www.exampledepot.com/egs/java.net/pkg.html
Related
Is there an option how to open a link using only console so for instance, If I enter 1 it will open a separate window where it will open my web link? I mean I want to use external links (URLs) where when I press 1 a chrome window will open with my URL. Is that possible and if so how, because I have only seen people do it using Java Swing. Any help would be great :)
Ok so I tried and this worked:
try {
Desktop desktop = java.awt.Desktop.getDesktop();
URI oURL = new URI("http://www.google.com");
desktop.browse(oURL);
} catch (Exception e) {
e.printStackTrace();
}
You will also need to implement URI and java.awt library
Your question is not clear enough to me, but what I understood is that you want to open the website link from the browser console, if that's what you mean you can do it using this javascript code
For external URLs :
window.location = 'http (s): // www.example.com'
and for the internal URLs :
__ window.location = '/ file.php'
or window.location = '/ file.html'
or window.location = '/ your_route'
As I understand your description you want to open a web link based on an input (1 in your case) in your Java console app. You can use the method exec as the follownig:
try {
Runtime.getRuntime().exec("explorer https://www.google.com");
} catch(Exception e) {
e.printStackTrace();
}
here the exec method calls a command which here I call Google Chrome to open Google.com.
Using this in Windows will open the default browser showing the website.
I'm working on my IRC Bot for Twitch.tv (pircbot API) and want to make the bot connect automatically to the stream's chat as soon the stream is going live.
I've found a Twitch API (here), but I have no clue
how I can implement this into my bot since I'm pretty new to Java.
Would be cool if someone could tell me any hints on how I could retrieve if a stream is online and how I can check the amount of viewers watching right now.
Greetings
I realize that this question was posted about a year ago, but I feel its important to have it answered just in case others stumble on this post. What Cam.Stokes said is spot on. It's the answer to the question. However the questioner indicated he is new to Java so I want to use code snippets to work out what Cam.Stokes said.
Catching if a stream is live isn't too difficult. The following code is a snippet from my bot. I got a thread that periodically receives the JSON data from the twitch API and then loads it into a JSON object. The JSON library that I'm using is called "minimal-json". Excellent lightweight lib if you ask me. When you review the code you can see what I'm doing; call twitch-api, get the JSON from the target stream, see if the "stream" object is filled with data. if so, stream is live, otherwise, not live.
import com.eclipsesource.json.JsonObject; // minimal-json specific
private static String TWITCH_STREAM = "https://api.twitch.tv/kraken/streams/$c$";
private static String insertChannel(String url, String channel)
{
return url.replace("$c$", channel );
}
public boolean isStreamLive()
{
try
{
URL url = new URL( insertChannel(TWITCH_STREAM, targetChannel) );
URLConnection conn = url.openConnection();
BufferedReader br = new BufferedReader( new InputStreamReader( conn.getInputStream() ));
String inputLine = br.readLine();
br.close();
JsonObject jsonObj = JsonObject.readFrom(inputLine);
return ( jsonObj.get("stream").isNull() )?false:true;
}
catch (IOException e)
{
e.printStackTrace();
}
return false;
}
Connecting the bot is rather straight forward with PircBot. Answered by Nicolai. Make sure you have an Oauth key from twitch that's linked to your bot account. The target channel is in lower case and with a # in front. And you should be good to go.
Good luck.
you need to get a auth key first
Link: http://twitchapps.com/tmi/
and then you need to set this in the main java file
bot.connect("irc.twitch.tv", 6667, "oauth:YOURAUTHKEY");
bot.joinChannel("#YOURCHANNEL-INLOWERCASE");
let me know if you have some other problems
Check out the chat section of the twitch API to see how to connect to the chat using PircBot:
https://github.com/justintv/Twitch-API/blob/master/IRC.md
As far as getting the live stream status, that is a little bit more difficult, but the url you want is:
https://github.com/justintv/Twitch-API/blob/master/v2_resources/streams.md#get-streamschannel
My suggestion would be to set a timed thread to check the stream status every 10 seconds or so, and if the "stream: " object in the json is not null, making the connection.
A good lib for parsing json (if you are doing twitch stuff, you will need to parse lots of json backwards and forwards by the looks) is gson.
(I need more than 10 rep to post more than 2 links apparently, but copy paste this without the space http:// code.google.com/p/google-gson/ )
I know that by using AT commands we can control the handset.As example unlocking screen we can give a specific AT command or moving right to the menu or left or bottom or up we can give specific AT commands. What all are the AT commands for doing this kind of control.
Thank you.
From what I understand, the AT commands are more used for phone-type functions (making calls, or sending SMS, etc), rather than menu navigation, etc.
I'm not entirely sure if that was your end-goal after menu navigation, but you can find more details here: http://en.wikipedia.org/wiki/Hayes_command_set (the original +AT command set)
If you wanted to send SMS from a handset connected to your computer you might want to take a peek at this page: http://www.developershome.com/sms/atCommandsIntro.asp
If you wanted more control when performing functions, like sending SMS, etc, you might want to investigate "PDU Mode."
It is entirely possible that some handset manufacturers may have implemented additional +AT commands to allow other functions to be performed, so you might do better by specifically searching for the commands related to the handset you are using.
(Of course, if you're having issues connecting to the handset hardware itself, you need to ensure you have either the javax.comm extension or some favoured Java USB API installed)
If post doesn't help, perhaps you could provide more details in your question? (eg. what you are ultimately trying to do, if you think it would help)
List of AT commands
sample java code to use AT command
public void servicesDiscovered(int transID, ServiceRecord serviceRecord[])
{
String url = serviceRecord[0].getConnectionURL(1, false);
try
{
//ClientSession conn= (ClientSession)Connector.open(url);
StreamConnection meineVerbindung = (StreamConnection) Connector.open(url);
if(conn== null)
System.out.println("Kann Service URL nicht oeffnen\n");
else
{
OutputStream out = conn.openOutputStream();
InputStream in = conn.openInputStream();
String message = "AT+CGMI\r\n";
// send AT-command
System.out.println("send AT Comand request: "+message);
out.write(message.getBytes());
out.flush();
out.close();
byte buffer[] = new byte[10000];
// read the response from mobile phone
in.read(buffer);
System.out.println("AT Comand response: "+buffer.toString());}
}
catch(IOException e)
{
System.out.println("Service Error(3): "+e.getMessage());
}
}
Please excuse my noobishness as I am teaching myself Java and don't know a lot.
I'm trying to make a multiplayer game that runs from Java applets, I have a server-side program working that will accept strings of text, but all my attempts to find code for applets have failed.
My best attempt looks like it works but I think fails to connect to the server, any ideas why? (localIP is my correct IP and works fine in other tests)
public void init()
{
try
{
socket = new Socket(localIP, 5555);
inStream = new DataInputStream(socket.getInputStream());
outStream = new PrintStream(socket.getOutputStream());
}
catch(Exception e)
{
never reached
}
}
I don't mind scrapping this if someone can tell me a better way to do it or any way at all.
a java applet can only connect to the server from which it was downloaded. if you are not loading the applet from localIP, then you will not be able to connect to it.
you may be able to get around this restriction by signing the applet.
Given that you are not using the Http Protocol, One assumes that the applet is loaded from another port other than 5555. If this is the case, the applet needs to be signed in order to do this functionality.
Anyone know any? I need to send in a http request and make sure the http response i got back is not http 500
I believe Hyperic HQ meets all of your criteria. It is open source, I believe it is written at least partially in Java, and it is designed to do all kinds of server monitoring.
It should be able to handle not only the kind of monitoring you requested but other necessary monitoring like memory, CPU usage, and disk space on your servers as well.
You could use httpunit - web-centric unit testing
While you find it you can use this:
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.IOException;
public class SimplisticMonitor {
public static void main( String [] args ) throws IOException {
HttpURLConnection c = ( HttpURLConnection )
new URL( "http://stackoverflow.com" ).openConnection();
System.out.println( c.getResponseCode() );
}
}
If you want to do this yourself, Apache HttpClient is an option:
GetMethod get = new GetMethod("http://www.stackoverflow.com");
try
{
int resultCode = client.executeMethod(get);
if (resultCode == 500)
{
//do something meaningful here
} // if
} // try
catch (Exception e)
{
e.printStackTrace();
}
finally
{
get.releaseConnection();
}
http-unit
Written in Java, HttpUnit emulates the relevant portions of browser behavior, including form submission, JavaScript, basic http authentication, cookies and automatic page redirection, and allows Java test code to examine returned pages either as text, an XML DOM, or containers of forms, tables, and links. When combined with a framework such as JUnit, it is fairly easy to write tests that very quickly verify the functioning of a web site.
or html-unit
HtmlUnit is a "GUI-Less browser for Java programs". It models HTML documents and provides an API that allows you to invoke pages, fill out forms, click links, etc... just like you do in your "normal" browser.
It has fairly good JavaScript support (which is constantly improving) and is able to work even with quite complex AJAX libraries, simulating either Firefox or Internet Explorer depending on the configuration you want to use.