trying to access a url from android activity - android

I want to access a url in my android activity, for storing a string thats passed as a parameter on the url itself with a webservice that i have built. at this point, i just want to access the url and see that it happens, and later on i will worry about doing something with the result (what the request returns back). I'm using HttpURLConnection. I'm getting this error:
D/SntpClient( 59): request time failed: java.net.SocketException: Address fami
ly not supported by protocol
my code is:
public void storeScore()
{
Log.d("storeScore","is running");
HttpURLConnection con = null;
//DefaultHttpClient
try {
URL url = new URL("http://www.google.com");
con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(10000);
con.setConnectTimeout(15000);
con.setRequestMethod("GET");
con.setDoInput(true); //also tried without this
con.setDoOutput(true); //also tried without this
con.connect();
Log.d("storeScore","got to connect");
//not really reading the result at this point:
//BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
//String payload = reader.readLine();
//reader.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("MalformedURLException",e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("IOException",e.getMessage());
e.printStackTrace();
}
}
the app android manifest includes both premissions:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
this method storeScore() is ran from a thread that is created onCreate and started. Am i doing something wrong here? If you need more relevant information that i didn't add here, tell me and I will edit the question. Thanks, i appreciate any assistance.

Related

[ANDROID]How to get HTML source from a URL(using WEBAPI for uTorrent)

I need to get a simple string out of the HTML code in a url.
FwyKvZJSZMLdgAlEuMvw7v_s9VhasprI-47KeavMegGJlvAC5ZLwng5gEFgAAAAA .
This is how it looks like. All I need is the string from the start.
This is the URL request I use to reach the code.
http://username:password#IP:8080/gui/token.html
The answers I found were either way too complicated or straight up didnt work (HTTPClient is now deprecated :( ).
This is what I have, but sadly it always returns java.io.FileNotFoundException: http://www.google.com and it does that on every website.
This is the code for it:
try {
System.out.println("TEST");
con = (HttpURLConnection) new URL("http://username:password#IP:8080/gui/token.html").openConnection();
con.setRequestMethod("GET");
con.setDoOutput(true);
con.setDoInput(true);
System.out.println(con.getOutputStream().toString());
InputStream response = con.getInputStream();
System.out.println("RMessage" + con.getResponseMessage());
con.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
con.setRequestProperty("Accept","*/*");
BufferedReader reader = new BufferedReader(new InputStreamReader(response));
for (String line; (line = reader.readLine()) != null; ) {
System.out.println(line + "NEKAJ SE JE ZGODILO V PRIDOBITVI");
}
reader.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (ProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
The link works alright in my Chrome App on my device.
Getting the source of something like Facebook.com or Google works alright too. I'm super confused.
EDIT: Printed the stacktrace:
10-26 11:45:52.816 3341-3721/com.example.davidvuckovic7.utorrentclient W/System.err: java.io.FileNotFoundException:
To avoid posting a separate thread for it, is there a way to customize URL's? To get user input username and password or user input IP?
Apparently I need to fix my cookies. Because browsers handle cookies automatically and my app doesn't, it causes issues. Tokens and cookies are apparently connected.
Now on to the next problem,

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.

HttpURLConnection: java.lang.IllegalStateException: Already connected

I'm trying to use HttpURLClient to send some POST data to a server using the HttpRestClient class shown below. When executing
conn.setDoInput(true);
I get
java.lang.IllegalStateException: Already connected
I uninstalled the app, and still get the same error.
In all the example I've seen openConnection is called before setDoInput. If, as its name suggests, openConnection opens a connection, it should never be used before `setDoInput, right? What am I missing?
Maybe at some point it crashed before executing disconnect. Could that be the reason? If so, how can I disconnect the old connection?
public class HttpRestClient {
static public int post(String urlStr, List<NameValuePair> data){
HttpURLConnection conn = null;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(data));
writer.flush();
writer.close();
os.close();
InputStream is = conn.getInputStream();
String dude = readIt(is);
return 1;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}
finally {
if(conn!=null) conn.disconnect();
}
}
}
This might be due to watches while debugging in your IDE. See this answer.
It happened to me and was hard to discover.
You called both of conn.setDoInput(true); and conn.setDoOutput(true);. Use one of them:
setDoOutput(true) is used for POST and PUT requests.
setDoInput(true) is used for GET request.
The connection you made was confused, it can't decide which request should be used.
In your code:
static public int post(String urlStr, List<NameValuePair> data){
HttpURLConnection conn = null;
System.setProperty("http.keepAlive", "false"); // must be set
try {
...
conn.setDoOutput(true);
conn.setRequestMethod("POST");
// and connect to server, if needed
conn.connect();
...
}
....
It may be a misleading exception. See this defect for Jersey-2 https://java.net/jira/browse/JERSEY-2729
The link has been updated:
https://github.com/javaee/jersey/issues/3001
Basically the issue is jersey was throwing invalid exception. The real issue in my case was that the connection was refused from the server.

Android --> java.net.ProtocolException: OutputStream unavailable because request headers have already been sent

I am trying for post data(username and password in JSON format for login) from android application to php server - drupal cms website using HttpUrlConnection .
Here is my code , For login.
I am getting this response:
java.net.ProtocolException: OutputStream unavailable because request
headers have already been sent!
I have searched on google & other stackoverflow questions but cant find any solution to my problem. So Please Help.
Thanks for listening.
HttpURLConnection httpcon = null;
int status = 0;
try {
httpcon = (HttpURLConnection) ((new URL("my URL here").openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
status = httpcon.getResponseCode();
httpcon.getHeaderFields();
System.out.println("===================>httpcon.getHeaderFields()"+httpcon.getHeaderFields());
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
httpcon.connect();
byte[] outputBytes = "{'username':'uname','password':'pass'}".getBytes("UTF-8");
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return status;
You call httpcon.getResponseCode() and httpcon.getHeaderFields() in the first part of your code. As mentioned in the javadoc for HttpUrlConnection, this causes the HTTP request to be executed. This makes sense, because to read the response header fields you need a response, and to get a response you have to issue the request.
You then do the output stream stuff, which fails because the request has already been sent.
To make this work, you need to re-order your code so that all the request stuff is set up before you access the response stuff. Something along these lines:
byte[] outputBytes = "{'username':'uname','password':'pass'}".getBytes("UTF-8");
try {
HttpURLConnection httpcon = (HttpURLConnection) ((new URL("my URL here").openConnection()));
//prepare the request
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect(); // May not be needed
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);
//get the response
status = httpcon.getResponseCode();
httpcon.getHeaderFields();
System.out.println("===================>httpcon.getHeaderFields()"+httpcon.getHeaderFields());
} //catch block left out

Android InputStream following a rewriterule

I'm trying to parse an xml file from a website. Let's say the website is "http://example.com"
This website has a htaccess rewrite rule setup to redirect anything with a "www" prefix to the host back to example.com. so "http://www.example.com" would redirect to "http://example.com"
In my code I have a URL that i get the InputStream of.
protected InputStream getInputStream() {
try {
return feedUrl.openConnection().getInputStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
In this case feedUrl is poingting to "http://www.example.com/file.xml" and when I do the following:
try {
Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler());
} catch (Exception e) {
throw new RuntimeException(e);
}
I get an exception thrown and I believe it's not redirecting to "http://example.com/file.xml"
I could obviously just statically change where my feedUrl variable is pointing to, but I need this to be dynamic.
If anyone ran into this problem like I did, then here's the solution. The HttpURLConnection is already setup to follow redirects by default if the response code is 300, 301, 302, or 303.
For some reason, the server I'm parsing from needs to have the response code be 307 which Android does not redirect automatically.
I would suggest using a different response code, but if your server needs it then here's work around.
HttpURLConnection conn = (HttpURLConnection) feedUrl.openConnection();
int responseCode = conn.getResponseCode();
if( responseCode == 307 ){
String location = conn.getHeaderField("location");
feedUrl = new URL(location);
conn = (HttpURLConnection) this.feedUrl.openConnection();
}
Now conn can open an input stream to the correct file.

Categories

Resources