malformedURLException when declaring URL with string in Android - android

According to Android reference you can declare an URL using a string.
That means that the next code is supposed to be correct(i.e):
URL url = new URL("http://www.android.com/");
When I try to use it I get:
"java.net.MalformedURLException"
It happens to me on AndroidStudio 1.2.1.1
The full code I'm trying to use comes from the references of HttpURLConnect of Android:
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
}

Look at this:
Java Malformed URL Exception
The answer says:
It is not raising the error, it's complaining that you haven't handled the possibility that it might, even though it won't, because the URL in this case is not malformed. Java seems to think this is a good idea. (It's not.)
To shut it up, add throws MalformedURLException or throws IOException to the method declaration. E.g.:
public void myMethod() throws IOException {
URL url = new URL("https://wikipedia.org/");
}

This works perfectly fine here
try {
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
urlConnection.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Related

Android Httpurlconnection issue - nothing happens after .connect

I am kind of new in android development and I am having a weird issue.
The following code is supposed to work:
URL url = new URL("http://127.0.0.1/test.html");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
System.out.println("code: "+code);
The problem is, after I do the connection.connect(); nothing happens, even if I add a textX.setText() after the connect, I am not able to do any action.
Any idea what might be the issue?
This is my whole method, all I am trying to do is get some text from the API, which says "OK" actually, but I am not able to make it work.
public void conn (View view)
{
TextView text2 = (TextView)findViewById(R.id.text2);
text2.setText("connecting...");
String output="";
//All working until here
URL url;
HttpURLConnection urlConnection = null;
try {
output="about to connect";
text2.setText(output);
url = new URL("http://127.0.0.1:4444/localweb/api/api.php");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream in = urlConnection.getInputStream();
text2.append("\nabout to get code");
int code = connection.getResponseCode();
text2.setText(Integer.toString(code));
//urlConnection = (HttpURLConnection) url.openConnection();
//urlConnection.connect();
//output=urlConnection.getResponseMessage();
//text2.setText(output);
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
output=output+current;
}
//text2.setText(output);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
There wasn't something 'wrong' with the http client code, the issue is that you cannot launch the httpurlclient from the parent thread as I was trying to do, it must be executed in the background through an AsyncTask, after moving all the httpurlconnection stuff into an additional async function now I am able to get all the web details I needed.

How to get XML data from https url in Android

I want to get XML data from the web server https://ruralfire.qld.gov.au/bushfirealert/bushfireAlert.xml
However, I can't do it because my codes always have an error "javax.net.ssl.SSLHandshakeException: Connection closed by peer".
And my InputStream is always null, so I can't do anything with it (such as parsing).
I ensure that the problem is in my connection but I don't know how to solve it.
This is my code in connecting to the web server:
private InputStream downloadUrl(String urlString) throws IOException {
URL url;
url = new URL(urlString);
InputStream is = null;
try {
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setDoInput(true);
is = con.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
May you help me to solve this problem ?
Thank you so much.

API call far faster on iOs and browser than on android

I have a trouble with my HttpsConnection on android.
First of all, no it is not a duplicate. I try almost all the solutions on SO, like changing the keep-alive option or the timeout ( and some of them indeed optimized a part of my code a little bit ) but it is still 5 to 10 times ( probably more ) slower on android than on iOS.
Sending a request to my server takes several seconds on android while it's almost instant on iOS and from a browser. I am sure that the server is not in cause. But it seems that getting the inputstream is terribly slow!
This line:
in=conn.getInputStream();
is the most delaying one, taking several seconds by itself.
My aim is to get a JSON from my server. My code is supposed to be technically as optimized as possible ( and it can probably help some people with HttpsConnection on the same time ):
protected String getContentUrl(String apiURL)
{
StringBuilder builder = new StringBuilder();
String line=null;
String result="";
HttpsURLConnection conn= null;
InputStream in= null;
try {
URL url;
// get URL content
url = new URL(apiURL);
System.setProperty("http.keepAlive", "false");
trustAllHosts();
conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(DO_NOT_VERIFY);
conn.setRequestMethod("GET");
conn.setRequestProperty(MainActivity.API_TOKEN, MainActivity.ENCRYPTED_TOKEN);
conn.setRequestProperty("Connection", "close");
conn.setConnectTimeout(1000);
in=conn.getInputStream();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((line=br.readLine())!= null) {
builder.append(line);
}
result=builder.toString();
//System.out.print(result);
br.close();
} catch (MalformedURLException e) {
result=null;
} catch (IOException e) {
result=null;
} catch (Exception e) {
result=null;
}
finally {
try {
in.close();
}catch(Exception e){}
try {
conn.disconnect();
}catch(Exception e){}
return result;
}
}
However, it keeps taking several seconds.
So I would like to know: is there a way to improve the speed of this API call? The problem is not the server or the JSON parsing but for sure the function above. Thanks a lot.

Simplest way to download text from URL

Is there a simplest way to download small text string from URL like this one:"http://app.georeach.com/ios/version.txt"
In iOS its pretty simple. But for android em not finding something good. what is the method for getting text like that from the above URL??
I used this code in onCreate of hello app,n app crashed:
try {
// Create a URL for the desired page
URL url = new URL("http://app.georeach.com/ios/version.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
StringBuilder sb = new StringBuilder(100);
while ((str = in.readLine()) != null) {
sb.append(str);
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
tv.setText(sb.toString());
} catch (MalformedURLException e) {
tv.setText("mal");
} catch (IOException e) {
tv.setText("io");
}
You have to create a new class extended from AsyncTask. You can't do network stuff in the main thread. It could work but you may not want to do that. Take a look at this link : http://developer.android.com/reference/android/os/AsyncTask.html
Also don't forget to add Internet permissions to your AndroidManifest.xml.
Try this:
URL url = new URL("http://bla-bla...");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream in = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
// your text is here
String text = sb.toString()
Do not forget to catch and handle IOException and close all streams.
An "easier" way would be this:
String url2txt = null;
try {
// Being address an URL instance
url2txt = new Scanner(address.openStream(), "UTF-8").useDelimiter("\\A").next();
} catch (IOException e) { ... }
The thing is what you consider "easier". As far as code goes, probably this is the shortest way, but it depends on what you want to do afterwards with the obtained text.

inoutstream from a website displays nothing

i used the following code to read line by line from a website using textview. But the problem is the textview displays nothing.
I would like to know where my mistake is or how to correct my code to read data from a website.
To Note: i use the emulator.
JAVA Code:
try {
URL url = new URL("http://www.google.com");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setDoOutput(true);
con.connect();
//readStream(con.getInputStream());
reader = new BufferedReader(new InputStreamReader (con.getInputStream()));
String line="";
while ( (line=reader.readLine()) != null)
tv00.setText(line);
} catch (Exception e) {
e.printStackTrace();
}
}

Categories

Resources