I am trying to create a GUI-based program in Java that has a 'Submit' button and when clicked, it takes you to a website.
I have read about the URL and URLConnection classes online and the connection to the website is established but the program does not open the link... This is what I have so far:
if(command.equals("Submit data"))
{
try {
URL myURL = new URL("http://google.com/");
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.connect();
}
catch (IOException t) {
// openConnection() failed
// ...
}
}
The connection seems to be established but I want the program to open up the browser and take to the website.. I've tried everything and no luck..
Thank you
You could either used a swing component like you can see in this thread --> Best Java/Swing browser component?
Otherwise use this snippet found at http://andy.ekiwi.de/?p=1026
public void openUrl(String url) throws IOException, URISyntaxException {
if(java.awt.Desktop.isDesktopSupported() ) {
java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
if(desktop.isSupported(java.awt.Desktop.Action.BROWSE) ) {
java.net.URI uri = new java.net.URI(url);
desktop.browse(uri);
}
}
}
Related
I am given a shortened url and I want to get the expanded form. The below java function is used to achieve this.
public String expand(String shortenedUrl){
URL url = null;
try {
url = new URL(shortenedUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
// open connection
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
} catch (IOException e) {
e.printStackTrace();
}
// stop following browser redirect
httpURLConnection.setInstanceFollowRedirects(false);
// extract location header containing the actual destination URL
String expandedURL = httpURLConnection.getHeaderField("Location");
httpURLConnection.disconnect();
return expandedURL;
}
The code works fine in Eclipse but the same doesn't work in android.
String expandedURL = httpURLConnection.getHeaderField("Location");
The above line throws java.lang.RuntimeException: Unable to start activity ComponentInfo. And the error is pointed to the above line. If I remove the above line no error is encountered. Even I am not able to use getResponseCode() function.
int status = 0;
try {
status = httpURLConnection.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
}
This piece of code also has the same problem. works in eclipse but not in android.
Any kind of help will be greatly appreciated.
Edit: The code using above function is,
ExpandUrl expandUrl = new ExpandUrl();
String expandedUrl = expandUrl.expand(shortenedUrl);
Note: The function expand is defined inside the class ExpandUrl.
Well, the code works in Eclipse but not in android. The reason is that you are doing it in Main thread and blocking it. Android wouldn't allow you to do so and throw runtime error.
I have tried to implement your code using AsyncTask in android. It works fine.
Give it a try.
To know more about AsyncTask follow: Android Documentation on AsyncTask
Good Luck!
I'm trying to write a String to my webpage using Java in Android Studio by reusing some piece of codes of one Java Eclipse project which works well on my PC.
However, the String just cannot be written to the web page using my Android phone.
public void upload(String FTPaddress, String message){
try {
URL url = new URL(FTPaddress); // my server address
URLConnection urlc = url.openConnection();
OutputStream os = (OutputStream) urlc.getOutputStream(); // To upload
OutputStream buffer = new BufferedOutputStream(os);
buffer.write(message.getBytes());
buffer.close();
os.close();
} catch (FileNotFoundException e) {
// print in log
} catch (IOException e) {
// print in log
}
}
Please note that the function is executed, the mobile phone is connected to the internet, thus I am running it on another thread using asyncTask, and there is no exceptions
So can anyone tell me why it worked on my laptop but not for my mobile phone?
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 8 years ago.
I know this question has been asked a lot on SO already so I apologize if it is redundant, but I can't seem to find an answer to my specific problem anywhere.
I'm attempting to connect my Android emulator to a localhost. Here is my connection code:
public void readPHP(String filename) throws IOException {
url = new URL("http://10.0.2.2:8000/" + filename);
URLConnection conn = url.openConnection();
InputStream stream = null;
try {
stream = conn.getInputStream();
} catch (IOException e) {
System.out.println(e.getMessage());
}
// more code....
stream.close();
}
I've also added the following line to my manifesto:
<uses-permission android:name="android.permission.INTERNET"/>
The app installs properly with no error messages but when I try to run it from the phone, it crashes with the vague message "Unfortunately, CodeGlass GDK has stopped." I'm sure this is a problem with Android because when I try to run the same code in a simple Java program it works as expected.
You are opening a connection in your UI Thread, which is causing an NetworkOnMainThreadException . Just put your code inside an AsyncTask, inside doInBackground() method, like this:
public class MyAsyncTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(String fileName) {
url = new URL("http://10.0.2.2:8000/" + filename);
URLConnection conn = url.openConnection();
InputStream stream = null;
try {
stream = conn.getInputStream();
} catch (IOException e) {
System.out.println(e.getMessage());
}
// more code....
stream.close();
return null;
}
}
You must use asynctask to get the data from url like they said.
But there is another way. İt is not advisable normally, but if you want to move on for now and get back and properly write an asynctask, you can use this piece of code for now;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Hope this helps.
I would like to know any java method can be used to check if the browser is closed.
I used the following code to open a default browser:
if(Desktop.isDesktopSupported()){
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI(url));
}
Then I want to perform some user actions on the opened website to capture the web traffic. After the browser is closed the web traffic will be saved.
So how can I determine if the browser is closed by using java code?
The best you can do is use Process builder:
public class Main {
public static void main(String[] args) {
try {
ProcessBuilder pb = new ProcessBuilder("C:\\Windows\\System32\\calc.exe");
Process p1 = pb.start();
p1.waitFor();
System.out.println(p1.exitValue());
} catch (Exception e) {
System.out.print(e);
}
}
}
You can launch a browser with the webpage as an argument and keep track of it like that.
I am using following code to load public shared images from google drive to android app, but sometimes I got:
javax.net.ssl.SSLException: Read error: ssl=0x1d9ed0: I/O error during system call, Connection reset by peer
Why google drive is closing connection before I download image? This is happening randomly, but quite often. Does someone collide with such problem?
public static InputStream getStream(String url)
{
InputStream is = null;
try
{
is = new URL(url).openConnection().getInputStream();
} catch (MalformedURLException e)
{
L.e(e.toString());
} catch (IOException e)
{
L.e(e.toString());
}
return is;
}
For bitmap loading I use simple code:
BitmapFactory.decodeStream(stream, null, null);
It could be that you are affected by the following: The URL that you get from the file's metadata is short lived. If you are saving that URL to use later it won't work because it could be that the URL gets invalidated.
To do this you have to fetch the image metadata every time to get the new downloadURL.
We are working on providing non expirable URLs in the future.