Android app using HttpURLConnection crashes at connect() - java

I have a following piece of code, basically copy-pasted from examples as I am new to Java and Android (not to programming):
URL vurl = new URL(voteurl); //vuteurl is a string containing a proper URL
HttpURLConnection hc;
hc=null;
hc = (HttpURLConnection)vurl.openConnection();
hc.setRequestMethod("GET");
hc.setDoOutput(true);
hc.setReadTimeout(10000);
hc.connect();
On the line "hc.connect();" the application crashes and Android informs me that it had been stopped.
Adding android.permission.INTERNET to the permisions used by the app did not help.

OK, turns out Android doesn't like network operations in the main thread.
Doing a request in a separate thread does the trick. Thanks guys for Your help!

URL vurl = null;
try {
vurl = new URL(voteurl);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} //vuteurl is a string containing a proper URL
HttpURLConnection hc;
hc=null;
try {
hc = (HttpURLConnection)vurl.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
hc.setRequestMethod("GET");
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hc.setDoOutput(true);
hc.setReadTimeout(10000);
try {
hc.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Related

How do i open all the links for a given URL using java?

Okay So I have the code to open up an URL using firebox. I'm just trying to find out how to open up all the links on that page, it can be done one at a time or all at once, but I just want to know. I can't seem to find this anywhere.
String url = "http://www.example.com";
if(Desktop.isDesktopSupported()){
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(new URI(url));
} catch (IOException | URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("xdg-open " + url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Why sendText calls throw timeout exception when using websockets?

I am new to websocket, and trying out with few examples. The application I created works fine for sometime say 10 - 15 mins, and from then on, it throws the timeout exception when sendText method is called on websocket session. I changed the value for "org.apache.tomcat.websocket.BLOCKING_SEND_TIMEOUT" to -1 and now it hangs.
could you please help me to resolve this issue.
The code I have written to send the data to websocket is as below:
public void update() {
Dashboard dashboardData = tunnelDataService.getDashboardData();
ObjectWriter ow = new ObjectMapper().writer();
String json = null;
try {
json = ow.writeValueAsString(dashboardData);
} catch (JsonGenerationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JsonMappingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
synchronized (lock) {
if (session.isOpen()) {
session.getBasicRemote().sendText(json);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am deploying this application on JBoss EAP 6.3.

Problems with BigClip

I have been trying to play music in my app. I've been using the example BigClip code:
try {
url = new URL(Sounds.class.getResourceAsStream("title1.wav").toString());
} catch (MalformedURLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
BigClip clip = new BigClip();
AudioInputStream ais = null;
try {
ais = AudioSystem.getAudioInputStream(url);
} catch (UnsupportedAudioFileException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
clip.open(ais);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
clip.start();
JOptionPane.showMessageDialog(null, "BigClip.start()");
clip.loop(4);
JOptionPane.showMessageDialog(null, "BigClip.loop(4)");
clip.setFastForward(true);
clip.loop(8);
// the looping/FF combo. reveals a bug..
// there is a slight 'click' in the sound that should not be audible
JOptionPane.showMessageDialog(null, "Are you on speed?");
}
When I only use title1.wav, I get this error:
java.net.MalformedURLException: no protocol: java.io.BufferedInputStream
When I add the protocol file://, I get a NullPointerException, although I can't see what could be causing that.
Am I using the wrong protocol, or have I done something else wrong? Thanks in advance!
Assuming your file is in the same package ("directory") as the Sounds class, use
url = Sounds.class.getResource("title1.wav");
because
new URL(Sounds.class.getResourceAsStream("title1.wav").toString())
is just bound not to work. You are calling toString on an instance of InputStream.
The NPE probably happens because AudioSystem.getAudioInputStream fails due to bad URL path so ais is null and BigClip throws NPE from open.

How do I turn off a program with a java code?

Hi guys I open in my java application I open a browser page with this code:
String URL = "https://www.google.com/";
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create(URL));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now I have to turn off the browser, Is there a code to do that?
No, there is no Java API to close the browser.
There sort-of is but it's not very reliable. But if you have to, you can try with keyboard shortcuts and mouse clicks using Java Robot API.
public class RobotTest {
public static void main(String[] args) {
String URL = "https://www.google.com/";
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create(URL));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Thread.sleep(3*1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Robot javaRobot;
try {
javaRobot = new Robot();
javaRobot.keyPress(KeyEvent.VK_ALT);
javaRobot.keyPress(KeyEvent.VK_F4);
javaRobot.keyRelease(KeyEvent.VK_ALT);
javaRobot.keyRelease(KeyEvent.VK_F4);
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

JSON io writer delete JSONObject on Android

I'm currently using the library JSON-io. I created a desktop application which when a person want to log in in the system send an JSONObject with his username and password. Then the server send back the response if the person is allowed or not (also a JSONObject). Until here everything works fine.
Now i want to make an Android app. I take the same code than before for login but the application crashes.
The code for login is launch from an AsyncTask and i put the permission to access to Internet to the Manifest.
I perform some testing and it occurs that the method write of JSONWriter "delete" my JSON because on the server side he receives this : {}. I tried to hardcode the JSONObject on the server side (the server's code works fine because we can use the desktop app) but this time the readObject on the android App receives also {}.
We tried to send jsonObject.toString() and this time it worked (except that the server isn't configured to handle a string).
Do anyone knows why on android the two methods write and readObject are deleting the JSON ?
Thank you.
EDIT:
Here the code i wrote:
On the android App
protected Boolean doInBackground(Void... params) {
// 3 : create a JSON object and send it to server for verification
JSONObject loginJS = new JSONObject();
try {
loginJS.put("type", Type.LOGIN); // Type is an enum
loginJS.put("username", userName);
loginJS.put("hash", mPassword);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
User user = new User();
System.out
.println("User created and ready to connect to the spu for login");
user.connexionToSPU(); // This method works
System.out.println("LoginJS = "+loginJS.toString()); At this point the print of the JSON is fine we have {"type":"Login", ....}
user.sendToSPU(loginJS); //This is where there's a problem
// 4 : wait response
JSONObject loginResponseJS = user.receiveFromSPU(); // And when i hard code the JSON on the server side receiveFromSPU get a empty JSON
Method connexionToSPU:
public void connexionToSPU() {
jswSPU = null;
jsrSPU = null;
Socket socket = null;
try {
socket = new Socket(prop.readPropertiesXML("IP_adress_server"),
Integer.parseInt(prop.readPropertiesXML("port_server")));
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
jswSPU = new JsonWriter(socket.getOutputStream());
jsrSPU = new JsonReader(new BufferedInputStream(socket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
sendToSPU method
public void sendToSPU(JSONObject json) {
try {
jswSPU.write(json);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ReceiveFromSPU method
public JSONObject receiveFromSPU() {
JSONObject json = null;
try {
json = (JSONObject) jsrSPU.readObject();
System.out.println("JSON FROM THE SERVER : "+json.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
Hope it will be sufficiently clear.
Thank you

Categories