How to handle exceptions with Jsoup in java to keep program running - java

my program crash when user inserts a weird url
It should go like
while(condition) {
try {
String url = reciveURL();
Document rss = Jsoup.connect( url ).get();
}
catch (MalformedURLException e) {
System.err.println("Invalid URL");
} catch (OthersExceptions e){
Others.Actions();
}
}
The problem is, this throws "java.net.MalformedURLException: no protocol", instead of printing "Invalid URL" and the program crash (when user inserts any other kind of text)
Thanks!

Lol, solved myself, but i'll let the question as theres no post on the same issue
You should import java.net.url, this brings the "URL" type, which triggers the MalformedURLException (Jsoup doesnt do this)
So it goes like this
while(true){
{
String url = reciveURL() ;
URL chk_url = new URL(url);
Document rss = Jsoup.connect( url ).get();
} catch (MalformedURLException e) {
System.err.println("url mal puesta!");
}
}

Related

Getting the url after clicking a link with HtmlUnit

So this is my first question here after reading like hundreds of threads in this forum :D.
I want to click an HtmlAnchor with HtmlUnit and retrieve the underlying url.
Maybe I am using the wrong methods or something, but here is the code that I tried so far:
public List<String> clickURLs(String searchAttribute) {
try {
wc.getOptions().setCssEnabled(false); wc.getOptions().setJavaScriptEnabled(false); wc.getOptions().setUseInsecureSSL(true); wc.getOptions().setPrintContentOnFailingStatusCode(false); wc.getOptions().setThrowExceptionOnFailingStatusCode(false); wc.getOptions().setThrowExceptionOnScriptError(false);
HtmlPage page = wc.getPage(url);
List<HtmlAnchor> links =page.getAnchors();
for (HtmlAnchor link: links) {
if(link.getTextContent().contains(searchAttribute)) {
String href =link.click().getWebResponse().toString();
System.out.println(href);
list.add(href);
}
}
} catch (Exception e) {
System.out.println("An error occured: " + e);
} // catch
finally {
wc.close();
} // finally
return list;
} // clickURLs()
Any help would be appreciated.

java.net.MalformedURLException in Intellij IDEA [duplicate]

How come this code is giving me a unhandled exception java.net.malformedurlexception in java ?
String u = "http://webapi.com/demo.zip";
URL url = new URL(u);
Can someone tell me how to fix?
You need to handle the posible exception.
Try with this:
try {
String u = "http://webapi.com/demo.zip";
URL url = new URL(u);
} catch (MalformedURLException e) {
e.printStackTrace();
}
Use a try catch statement to handle exceptions:
String u = "http://webapi.com/demo.zip";
try {
URL url = new URL(u);
} catch (MalformedURLException e) {
//do whatever you want to do if you get the exception here
}
java.net.malformedurlexception
It means that no legal protocol could be found in a specification string or the string could not be parsed or your URL is not confirmed the spec or missing a component
I think this will help you to understand URL
https://url.spec.whatwg.org/

DELETE Request in Android doesn't connect to server

So my question is how can I create a DELETE Request to an URL in Android Studio Java. I already have an Async Task which GET json from URL. So my question now is how can I create a DELETE request
EDIT:
So right now I got this code:
int pos = arrlist.get(info.position).getId();
URL_DELETE = "http://testserver/test/tesst.php?id=" + pos + "&username=" + username + "&password=" + password;
URL url = null;
try {
url = new URL(URL_DELETE);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
"Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
To understand the content of the given URL should be deleted. But if I run the code nothing happens.
You need to call connect() on the HttpURLConnection. Right now you're not actually making a connection to the server.
Based on your comments on the other answer, you're also trying to run this code on the main (UI) thread - you'll need to change your code to run on a background thread.
If you're using OkHttp:
Request request = new Request.Builder().delete().url(url).build();
Response rawResponse = null;
try {
rawResponse = new OkHttpClient().newCall(request).execute();
} catch (IOException e) {
System.err.println(e.getMessage());
}
String responseAsString = rawResponse.body().string();

Getting a null value when attempting to get KML node value from phone, but not on the emulator with android

I am currently designing an application that needs to plot a route on a MapView. For this to function correctly I need to get data from a KML document that i get from:
http://maps.google.com/maps?f=d&hl=en&saddr=-33.882993,18.63486&daddr=-33.870162,18.657837&ie=UTF8&0&om=0&output=kml
I have created a test project to ensure that this data is received correctly. The problem is that it runs perfectly on my emulator, but not on the actual android phone.
The following piece of code starts a thread when a button is clicked, getting an input stream response (KML).
public void onClick(View v) {
if (v.getId()== R.id.btn1)
{
new Thread() {
#Override
public void run() {
String url = "http://maps.google.com/maps?f=d&hl=en&saddr=-33.882993,18.63486&daddr=-33.870162,18.657837&ie=UTF8&0&om=0&output=kml";
InputStream is = getConnection(url);
mRoad = RouteProvider.getRoute(is);
mHandler.sendEmptyMessage(0);
}
}.start();
}
}
private InputStream getConnection(String url) {
InputStream is = null;
try {
HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
conn.connect();
is = conn.getInputStream();
conn = null;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
For the moment, all getRoute() needs to do is give the contents of the "LineString" element inside the KML Document. These contents are a list of coordinates that can be used to draw a route.
public class RouteProvider {
/** Gets data from KML response **/
public static Road getRoute(InputStream is) {
Road road = new Road();
try
{
Document xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
NodeList a = xmlDoc.getElementsByTagName("LineString");
System.out.println(a.item(0).getTextContent());
road.mName = a.item(0).getTextContent();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
return road;
}
On the emulator I am running the correct value is displayed within road.mName, which is a list of coordinates. On a Android phone it displays null?
I am building for Android 2.3.3 on eclipse and I used a Samsung Galaxy S2 for testing.
Did not need to use KML after all. Just used google maps to supply xml format. Much easier.
https://developers.google.com/maps/documentation/directions/

how to resume code operation after handle exception?

Q : How to resume code operation after a handled exception ?
i now using try and catch.
Try
{
Process url and render the text and save contents to text file.
}Catch(Exception ex)
}
Some urls are broken, so how do i skip broken urls and continue with other urls ?
Depends on how you iterate over your URLs. For example:
for (URL url: urllist) {
try {
// Process **one** url
} catch (Exception ex) {
// handle the exception
}
}
This will process all urls in the list, even if some of the processing raises an exception.
That's it - do nothing (apart from perhaps logging a warning), and the code execution will continue. Ex:
for (String url : urls) {
try {
// parse, open, save, etc.
} catch (Exception ex) {
log.warn("Problem loading URL " + url, ex);
}
}
Try this:
for (url : allUrls) {
try {
Process url and render the text and save contents to text file.
} catch(Exception ex) {
...
continue;
}
}
There is a logical error in this pseudo-code.
Think about it like this. Your 'process url' was a loop yes? When it found an exception it exited the process loop to the catch block and then to the end of the algorithm.
You need to nest the entire try catch block in the process loop. That way when it hits an exception it returns to the begging of the loop and not to the end of the program.
Create two methods like this:
public void processAllURLs(final List<String> urls){
for(String url: urls){
processURL(url);
}
}
public void processURL(final String url){
try {
// Attempt to process the URL
} catch (Exception ex) {
// Log or ignore
}
}

Categories