Skip to content

Instantly share code, notes, and snippets.

@guinso
Last active April 12, 2017 05:52
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 guinso/9d3892124b268d6bf80f9bedbf644ec3 to your computer and use it in GitHub Desktop.
Save guinso/9d3892124b268d6bf80f9bedbf644ec3 to your computer and use it in GitHub Desktop.
Sample code demo retrieve HTTP request content for Android Mashmallow
package com.example.guinso.restclientdemo;
import android.os.AsyncTask;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//example bind event to Floating Action Button (you can bind with any control event)
FloatingActionButton fbReload = (FloatingActionButton)findViewById(R.id.fbReload);
fbReload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("MainActivity", "Reload is triggered.");
//make HTTP REST request in async task
//(since Android constraint network execution must not run in main loop)
AsyncTask<String, Void, String> tass = new AsyncTask<String, Void, String>() {
//this is where to run HTTP request execution
@Override
protected String doInBackground(String... params) {
//since this example only pass url, so definitely is first parameter
String raw = getHttpContentString(params[0]);
return raw;
}
//this is where you update your GUI content after retrieve from HTTP request
@Override
protected void onPostExecute(String result) {
Log.d("MainActivity", result);
}
};
//replace with your targeted url (this is just an example)
tass.execute("http://192.168.0.44:7777/api/meals");
}
});
}
private String getHttpContentString(String requestUrl) {
URL url = null;
try {
url = new URL(requestUrl);
} catch (MalformedURLException e) {
Log.e("mainActivity", String.format("URL %s is not valid", requestUrl));
url = null;
}
//exit scope if URL is invalid
if(url == null) {
//TODO: notify failed to reload content
return "";
}
//start pull content from REST server
HttpURLConnection httpConn = null;
String responseContent = "";
try {
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("GET");
//read HTTP response code and decide whether continue or not
int responseCode = httpConn.getResponseCode();
if(responseCode != 200)
{
Log.e("mainActivity", "Fail to get content from " + requestUrl);
responseContent = "";
} else {
//get content character set (default set to UTF-8)
String charset = httpConn.getContentEncoding();
if(charset == null || charset.equals(""))
charset = "UTF-8";
//decode input stream to string
InputStream in = httpConn.getInputStream();
ByteArrayOutputStream readBuffer = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int readLen = 0;
while((readLen = in.read(buffer)) != -1) {
readBuffer.write(buffer, 0, readLen);
}
responseContent = readBuffer.toString(charset);
}
}
catch (IOException ex) {
ex.printStackTrace();
responseContent = "";
} finally {
if(httpConn != null)
httpConn.disconnect();
}
return responseContent;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment