Skip to content

Instantly share code, notes, and snippets.

@hnaoto
Last active November 2, 2021 21:52
Show Gist options
  • Save hnaoto/f492c9ceae264897dd6f to your computer and use it in GitHub Desktop.
Save hnaoto/f492c9ceae264897dd6f to your computer and use it in GitHub Desktop.
Make HTTP request and parse JSON data from Android by using HttpURLConnection
//The original sample is from here: http://syntx.io/how-to-send-an-http-request-from-android-using-httpurlconnection/
//Deprecated funcitons and non-working code are modeifed.
//For more reference, please visit: http://developer.android.com/reference/java/net/HttpURLConnection.html
//I am using Google Books APIs for this sample.
//The returned book objects might have different format according to the language/country. (The second book obejct in data.json is the Japanese version)
//execute the AsyncTask some place in the UI thread
//new CatalogClient().execute("https://www.googleapis.com/books/v1/mylibrary/bookshelves/3/volumes?country=US");
public class CatalogClient extends AsyncTask<String, String, List<Book>> {
@Override
protected List<Book> doInBackground(String... params) {
URL url;
HttpURLConnection urlConnection = null;
List<Book> books= new ArrayList<>();
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
//HTTP header
urlConnection.setRequestProperty("Authorization", "Bearer "+ token);
int responseCode = urlConnection.getResponseCode();
String responseMessage = urlConnection.getResponseMessage();
if(responseCode == HttpURLConnection.HTTP_OK){
String responseString = readStream(urlConnection.getInputStream());
Log.v("CatalogClient-Response", responseString);
books = parseBookData(responseString);
}else{
Log.v("CatalogClient", "Response code:"+ responseCode);
Log.v("CatalogClient", "Response message:"+ responseMessage);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(urlConnection != null)
urlConnection.disconnect();
}
return books;
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
private List<Book> parseBookData(String jString){
List<Book> bookList = new ArrayList<Book>();
try {
JSONObject jObj = new JSONObject(jString);
String totalItems= jObj.getString("totalItems");
Log.v("totalItems",totalItems);
if (Integer.parseInt(totalItems) == 0) {
((TextView) findViewById(R.id.JSON_value)).setText("You have no books in this shelf");
} else {
JSONArray items = jObj.getJSONArray("items");
if(items != null) {
for (int i = 0; i < items.length(); i++) {
String title = items.getJSONObject(i).getJSONObject("volumeInfo").getString("title");
String picURL = items.getJSONObject(i).getJSONObject("volumeInfo").getJSONObject("imageLinks").getString("thumbnail");
String isbn = items.getJSONObject(i).getJSONObject("volumeInfo").getJSONArray("industryIdentifiers").getJSONObject(1).getString("identifier");
//the value of progress is a placeholder here....
Book book = new Book(title, picURL, isbn, 0);
bookList.add(book);
Log.v("bookList", "Title "+ title + "thumbnail "+ picURL + "isbn " + isbn);
}
}
}
} catch (JSONException e) {
Log.e("CatalogClient", "unexpected JSON exception", e);
}
return bookList;
}
protected void onPostExecute(List<Book> books) {
super.onPostExecute(books);
//make use of data..
}
}
public class Book {
private String title;
private String picURL;
private String isbn;
private double progress;
public Book(String title, String picURL, String isbn, double progress){
this.title = title;
this.picURL = picURL;
this.isbn = isbn;
this.progress = progress;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPicURL() {
return picURL;
}
public void setPicURL(String picURL) {
this.picURL = picURL;
}
public String getIsbn() {
return isbn;
}
public double getProgress() {
return progress;
}
}
{
"kind": "books#volumes",
"totalItems": 2,
"items": [
{
"kind": "books#volume",
"id": "JV6rpwAACAAJ",
"etag": "7NWBjOkpxiI",
"selfLink": "https://www.googleapis.com/books/v1/volumes/JV6rpwAACAAJ",
"volumeInfo": {
"title": "Node.js in Action",
"authors": [
"Mike Cantelon",
"T. J. Holowaychuk",
"Marc Harter",
"Nathan Rajlich"
],
"publisher": "Manning Publications",
"publishedDate": "2013-07-28",
"description": "Provides information on using Node.js to build scalable Web applications, covering such topics as asynchronous programming, data storage, and output templating.",
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "1617290572"
},
{
"type": "ISBN_13",
"identifier": "9781617290572"
}
],
"readingModes": {
"text": false,
"image": false
},
"pageCount": 395,
"printType": "BOOK",
"categories": [
"Computers"
],
"averageRating": 3.5,
"ratingsCount": 14,
"maturityRating": "NOT_MATURE",
"allowAnonLogging": false,
"contentVersion": "preview-1.0.0",
"imageLinks": {
"smallThumbnail": "http://books.google.com/books/content?id=JV6rpwAACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api",
"thumbnail": "http://books.google.com/books/content?id=JV6rpwAACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api"
},
"previewLink": "http://books.google.com/books?id=JV6rpwAACAAJ&hl=&source=gbs_api",
"infoLink": "http://books.google.com/books?id=JV6rpwAACAAJ&hl=&source=gbs_api",
"canonicalVolumeLink": "http://books.google.com/books/about/Node_js_in_Action.html?hl=&id=JV6rpwAACAAJ"
},
"userInfo": {
"updated": "2015-09-22T20:19:42.945Z"
},
"saleInfo": {
"country": "US",
"saleability": "NOT_FOR_SALE",
"isEbook": false
},
"accessInfo": {
"country": "US",
"viewability": "NO_PAGES",
"embeddable": false,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED",
"epub": {
"isAvailable": false
},
"pdf": {
"isAvailable": false
},
"webReaderLink": "http://books.google.com/books/reader?id=JV6rpwAACAAJ&hl=&printsec=frontcover&output=reader&source=gbs_api",
"accessViewStatus": "NONE",
"quoteSharingAllowed": false
}
},
{
"kind": "books#volume",
"id": "Y81uAAAACAAJ",
"etag": "C5B+LugISuU",
"selfLink": "https://www.googleapis.com/books/v1/volumes/Y81uAAAACAAJ",
"volumeInfo": {
"title": "源氏物",
"subtitle": "全代",
"authors": [
"紫式部"
],
"publishedDate": "1978",
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "4061582275"
},
{
"type": "ISBN_13",
"identifier": "9784061582279"
}
],
"readingModes": {
"text": false,
"image": false
},
"pageCount": 166,
"printType": "BOOK",
"maturityRating": "NOT_MATURE",
"allowAnonLogging": false,
"contentVersion": "preview-1.0.0",
"previewLink": "http://books.google.com/books?id=Y81uAAAACAAJ&hl=&source=gbs_api",
"infoLink": "http://books.google.com/books?id=Y81uAAAACAAJ&hl=&source=gbs_api",
"canonicalVolumeLink": "http://books.google.com/books/about/%E6%BA%90%E6%B0%8F%E7%89%A9%E8%AA%9E.html?hl=&id=Y81uAAAACAAJ"
},
"userInfo": {
"updated": "2015-09-22T20:19:09.245Z"
},
"saleInfo": {
"country": "US",
"saleability": "NOT_FOR_SALE",
"isEbook": false
},
"accessInfo": {
"country": "US",
"viewability": "NO_PAGES",
"embeddable": false,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED",
"epub": {
"isAvailable": false
},
"pdf": {
"isAvailable": false
},
"webReaderLink": "http://books.google.com/books/reader?id=Y81uAAAACAAJ&hl=&printsec=frontcover&output=reader&source=gbs_api",
"accessViewStatus": "NONE",
"quoteSharingAllowed": false
}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment