Ping remote server and wait to get data

Posted by infinity on Stack Overflow See other posts from Stack Overflow or by infinity
Published on 2011-11-21T01:43:03Z Indexed on 2011/11/21 1:51 UTC
Read the original article Hit count: 213

Filed under:
|
|

Hi I'm building my first application for android and I've reached a point where I can't find a solution even have no idea what to search for in Google.

So the problem: I am pinging a remote server with GET request through the application passing some parameters like file_id. Then the server gives back confirmation if the file exists or error otherwise, both in plain text. The error string is $$$ERROR$$$. Actually the confirmation is JSON string that holds the path to the file. If the file doesn't exists on the server it generated the error message and start downloading the file and processing it which normally takes 10-30 seconds. What would be the best way to check if the file is ready for download? I have DownloadFile class that extends AsyncTask but before I reach the point to download the file I need the URL which is dependant on the previous request which is in the main class in the UI thread. Here is some code:

public class MainActivity extends Activity {        
        private String getInfo() {
        // Create a new HttpClient and Post Header
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpPost = new HttpGet(infoUrl);
        StringBuilder sb = null;
        String data;
        JSONObject jObject = null;

        try {
            HttpResponse response = httpClient.execute(httpPost);
            // This might be equal "$$$ERROR$$$" if no file exists
            sb = inputStreamToString(response.getEntity().getContent());
        } catch(ClientProtocolException e) {
            // TODO Auto-generated catch block
            Log.v("Error: pushItem ClientProtocolException: ", e.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.v("Error: pushItem IOException: ", e.toString());
        }

        // Clean the data to be complaint JSON format
        data = sb.toString().replace("info = ", "");
        try {
            jObject = new JSONObject(data);
            data = jObject.getString("h");
            fileTitle = jObject.getString("title");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        downloadUrl = String.format(downloadUrl, fileId, data);

        return downloadUrl;
    }
}

So my idea was to get the content and if equal to $$$ERROR$$$ go into loop until JSON data is passed but I guess there is better solution. Note: I don't have control over the server output so have to deal with what I have.

© Stack Overflow or respective owner

Related posts about android

Related posts about file-download