i hope you can help me with my problem. I have to instantiate an http connection and do a get call to the server.
After this call i have to check periodically if the server sent me some data (the connection must not be closed after the first data received). If it does, then i have to parse this data and pass it to an activity and wait again.
My problem is to understand if i’m doing correctly this thing. Here my code
try {
URL url = getUrl();
URLConnection urlConn = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) urlConn;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
while(true) {
sleep(5000);
int responseCode = httpConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConnection.getInputStream();
String response = null;
if(inputStream.available() > 0) {
long length = inputStream.available();
byte[] bytes = new byte[(int) length];
inputStream.read(bytes);
response = new String(bytes, "UTF-8");
}
}
}
} catch(Exception e) {
e.printStackTrace();
}
getUrl() function gives me the complete url that i have to call.
Then i connect through httpConnection.connect();.
while i’m iterating is the connection already opend and capable of receiving incoming data?
I apologize for my english. Thanks a lot
Francesco
From the official android documentation
As you see from this quote, if you need to send some data to a host you just need to call
setDoOutput(true)and useOutputStreamof your connection to send data to the host. In this case you use "POST" request method after you calledsetDoOutput(true). If you don’t need to send data, but just to connect to the host and retrieve data, you also don’t need to callsetRequestMethod("GET"), because it’s default request method.When you connect to the host, just use
InputStreamto get data from it.