Skip to content

Instantly share code, notes, and snippets.

@chicofilho
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chicofilho/1c0c34cb4fa0cb04095e to your computer and use it in GitHub Desktop.
Save chicofilho/1c0c34cb4fa0cb04095e to your computer and use it in GitHub Desktop.
The way I manage POST and GET in Android Apps
/* this is not a mandatory class for the process of doing HTTP requests. It is only neccessary for those working with API.
* it is important to notice that it might be changed regarding the needs of the project
*/
package br.com.say2me.app.async;
import br.com.say2me.app.MainActivity;
import android.os.AsyncTask;
public class AuthLayer extends AsyncTask<Object, Object, Object>{
private MainActivity activity;
private int status;
public AuthLayer(MainActivity activity){
this.activity = activity;
}
// This method can be implemented in children classes as needed (GET/POST)
@Override
protected Object doInBackground(Object... params) {
return null;
}
// This method is used to ensure that all children classes of authLayer do an authorization prosess in case of 401
@Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
this.checkAuth();
this.postExecuteAction(result);
}
// This is the method to be called on after execution processes
protected void postExecuteAction(Object result){}
protected void checkAuth(){
if(this.status == 401){ // if it gets authorization problems
new SendAuthData(this.activity).execute(); // utilizes another class to handle the authorization
}
}
// helper methods needed in childrend classes to access the status of the resquest
protected MainActivity getActivity(){
return this.activity;
}
protected void setProtocolStatus(int status){
this.status = status;
}
protected int getProtocolStatus(){
return this.status;
}
}
// Normal GET approach with AuthLayer. Remember to implement the method postExecuteAction as needed
package br.com.say2me.app.async;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.message.BasicNameValuePair;
import br.com.say2me.app.MainActivity;
import br.com.say2me.app.config.ConfigManager;
import br.com.say2me.app.model.Auth;
public class GET extends AuthLayer{
private String url;
private List<BasicNameValuePair> data;
public GET(MainActivity activity, String url) {
super(activity);
this.url = url;
// I have a class to handle my Authorization parameters
Auth auth = this.getActivity().getFacade().getAuth();
// This is a specific point of the project, as no GET request uses other parameter beyond the token
this.data = null;
this.checkData();
this.data.add(new BasicNameValuePair("token",auth.getToken()));
}
// if there is no data, initializes an empty array.
private void checkData() {
if(this.data == null)
this.data = new ArrayList<BasicNameValuePair>();
}
// be aware to implement the method postExecuteAction after the execution of the GET, in case you want to add other functionalities
@Override
protected Object doInBackground(Object... params) {
try {
return downloadUrl();
} catch (IOException e) {
return "error";
}
}
private String downloadUrl() throws IOException {
InputStream is = null;
String contentAsString = "";
try {
URL url = this.getParsedUrl();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(50000);
conn.setConnectTimeout(55000);
String basicAuth = "Token token=" + ConfigManager.AUTH_TOKEN;
conn.setRequestProperty ("Authorization", basicAuth);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
int status = conn.getResponseCode();
this.setProtocolStatus(status);
if(status == 200){
is = conn.getInputStream();
contentAsString = readIt(is);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
is.close();
}
}
return contentAsString;
}
private URL getParsedUrl() throws MalformedURLException {
URL url = null;
String urlTemp = this.url;
if(this.data.size()>0)
urlTemp = urlTemp+"?";
for (BasicNameValuePair bs : this.data) {
urlTemp = urlTemp+"&"+bs.getName()+"="+bs.getValue();
}
url = new URL(urlTemp);
return url;
}
public String readIt(InputStream stream) throws IOException {
Reader reader = null;
reader = new InputStreamReader(stream);
String buffer = "";
int content = 0;
while(content != -1){
content = reader.read();
buffer += (char) content;
}
reader.close();
return buffer;
}
}
package br.com.say2me.app.async;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import br.com.say2me.app.MainActivity;
import br.com.say2me.app.config.ConfigManager;
public class POST extends AuthLayer{
private String url;
private List<BasicNameValuePair> data;
public POST(MainActivity activity, String url, List<BasicNameValuePair> data) {
super(activity);
this.url = url;
this.data = data;
// especifico dos casos de uso deste projeto
if(data == null){
this.data = new ArrayList<BasicNameValuePair>();
}
this.data.add(new BasicNameValuePair("token_t", "t"));
this.data.add(new BasicNameValuePair("token", this.getActivity().getFacade().getAuth().getToken()));
this.data.add(new BasicNameValuePair("imei", this.getActivity().getImei()));
}
@Override
protected Object doInBackground(Object... params) {
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(this.url);
httpPost.addHeader("Authorization", "Token token="+ConfigManager.AUTH_TOKEN);
// Request parameters and other properties.
httpPost.setEntity(new UrlEncodedFormEntity(this.data, "UTF-8"));
// 3. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 4. receive response as inputStream
InputStream inputStream = httpResponse.getEntity().getContent();
// 5. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
int status = httpResponse.getStatusLine().getStatusCode();
// 6. sets the status, so the AuthLayer can work normally;
this.setProtocolStatus(status);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return result;
}
protected String getURL(){
return this.url;
}
protected String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
@chicofilho
Copy link
Author

  • The gists have the intention of being used as an example and reference while building GET and POST approaches on Android App
  • They are an extension of the original process created by @lfliborio
  • Feel free to update, comment and ask

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment