Gallery3:API:REST:Java-Android - Gallery Codex
Personal tools

Gallery3:API:REST:Java-Android

From Gallery Codex

Uploading an item, using Java, an Android 1.5+ SDK and Apache Commons HttpClient

BACKGROUND

This is, by no means, the only way to accomplish this transaction; check Google for alternate implementations. For this implementation there are: Pros: reduced lines of code, small dependency storage footprint, it works. Cons: dependencies not included in Android SDK release. Also, this is a simple code example that could be enhanced/refined significantly.



    private Boolean uploadItem(String albumUrl, String filePath)
    {
        //Create the HttpClient, then the POST
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(albumUrl);

        //Specify the request method
        httpPost.addHeader("X-Gallery-Request-Method", "post");
        
        //Specify the request key: (_prefs == reference to shared preferences)
        httpPost.addHeader("X-Gallery-Request-Key", _prefs.getString("API_KEY", ""));

        //Multipart; pay particular attention to the BROWSER_COMPATIBLE
        MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        //The file we will be uploading
        File upFile = new File(filePath);
        
        try {
            
            //Create a JSON object to be used in the StringBody
            JSONObject jsonObj = new JSONObject();
            
            //Add some values
            jsonObj.put("name", upFile.getName());
            jsonObj.put("type", "photo");
            
            //Add the JSON "part"
            mpEntity.addPart("entity", new StringBody(jsonObj.toString()));
        }
        catch (JSONException je) {
            Log.v(TAG, je.getMessage());
        }
        catch (UnsupportedEncodingException ue) {
            Log.v(TAG, ue.getMessage();
        }

        //The file body, eventually added to the multipart entity
        FileBody fBody = new FileBody(upFile);

        //Add the part
        mpEntity.addPart("file", fBody);

        //Set the entity
        httpPost.setEntity(mpEntity);

        try {
  
            //Execute the request "POST"
            HttpResponse httpResp = httpClient.execute(httpPost);
            
            //Check the status code, in this case "created"
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED)
                    return true;
        }
        catch (Exception e) //General; more specific ClientProtocolException & IOException
        {
            Log.v(TAG, e.getMessage());
        }

        //Throw, return false..either way, we failed
        return false;
    }