Skip to content

Instantly share code, notes, and snippets.

@maxivak
Last active October 29, 2015 08:37
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 maxivak/22b492bc1552e8165875 to your computer and use it in GitHub Desktop.
Save maxivak/22b492bc1552e8165875 to your computer and use it in GitHub Desktop.
Android. Utils: Get JSON data by URL, download bitmap
package com.maxivak.utils;
import java.io.*;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.util.List;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.http.AndroidHttpClient;
import android.os.StrictMode;
import android.util.Log;
public class myutils {
public static JSONArray getJSONArrayfromString(String data) {
try {
JSONArray a = new JSONArray(data);
return a;
} catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString()+". ");
return null;
}
}
public static JSONArray getJSONArrayfromURL(String url, List<NameValuePair> valuePairs) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String result = "";
try {
//HttpClient httpclient = new DefaultHttpClient();
//HttpPost httppost = new HttpPost(url);
//httppost.setEntity(new UrlEncodedFormEntity(valuePairs));
URL srv = new URL("" + url );
URLConnection connection = srv.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection;
InputStream is = httpConnection.getInputStream();
//BOMInputStream is = new BOMInputStream(httpConnection.getInputStream());
//HttpResponse response = httpclient.execute(httppost);
//HttpEntity entity = response.getEntity();
//InputStream is = entity.getContent();
//
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF8"),8);
removeBOM(reader);
//
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
//
JSONArray array = new JSONArray(result);
return array;
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString()+". "+result);
return null;
}
}
public static JSONObject getJSONfromURL(String url){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
//
String result = "";
try{
result = getStringfromURL(url, false);
}
catch (FileNotFoundException e){
return null;
}
// json parse
JSONObject res = null;
try{
res = new JSONObject(result);
return res;
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
catch (Exception e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return null;
}
public static String getStringfromURL(String url, boolean throwException)
throws FileNotFoundException
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String result = "";
try {
URL srv = new URL("" + url );
URLConnection connection = srv.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection;
InputStream is = httpConnection.getInputStream();
//
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF8"),8);
removeBOM(reader);
//
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e){
Log.e("error", "Error getting data from URL: "+e.toString());
if (throwException){
Log.e("error", "throw not found");
throw new FileNotFoundException();
}
return "";
}
return result;
}
public static String getStringFromFile(File file){
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
}
}
catch (IOException e) {
//e.printStackTrace();
return "";
}
return text.toString();
}
public static void writeStringToFile(File file, String s){
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
OutputStreamWriter os = new OutputStreamWriter(fos);
os.write(s);
os.close();
fos.close();
} catch (Exception e) {
//e.printStackTrace();
}
}
public static void writeSetToFile(File file, Set<String> data){
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
OutputStreamWriter os = new OutputStreamWriter(fos);
os.write("[");
os.write(joinItems(data, ",", true));
os.write("]");
os.close();
fos.close();
} catch (Exception e) {
//e.printStackTrace();
}
}
public static String joinItems(Set<String> items, String delim, Boolean includeQuotes) {
StringBuilder sb = new StringBuilder();
int i = 0;
for (String s : items)
{
if (i>0){
sb.append(delim);
}
if (includeQuotes){
sb.append("\""+s+"\"");
}
else{
sb.append(s);
}
//
i++;
}
return sb.toString();
}
/*
public static String getStringfromURL(String url){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
//initialize
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF8"),8);
removeBOM(reader);
//
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return result;
}
*/
/*
public static ArrayList<String> FromJSONtoArrayList(String url)
{
ArrayList<String> listItems = new ArrayList<String>();
String result1[] = null;
try {
URL json = new URL(url);
URLConnection jc = json.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
JSONArray jsonArray = jsonResponse.getJSONArray("GetDataResult");
HashMap<String, String> map = new HashMap<String, String>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jObject = (JSONObject)jsonArray.get(i);
listItems.add(jObject.getString("name")+","+"\n " +jObject.getString("age") );
}
reader.close();
} catch(Exception e){
}
return listItems;
}
}
*/
private static char[] UTF32BE = { 0x0000, 0xFEFF };
private static char[] UTF32LE = { 0xFFFE, 0x0000 };
private static char[] UTF16BE = { 0xFEFF };
private static char[] UTF16LE = { 0xFFFE };
private static char[] UTF8 = { 0xEFBB, 0xBF };
private static boolean removeBOM(Reader reader, char[] bom) throws Exception {
int bomLength = bom.length;
reader.mark(bomLength);
char[] possibleBOM = new char[bomLength];
reader.read(possibleBOM);
for (int x = 0; x < bomLength; x++) {
if ((int) bom[x] != (int) possibleBOM[x]) {
reader.reset();
return false;
}
}
return true;
}
private static void removeBOM(Reader reader) throws Exception {
if (removeBOM(reader, UTF8)) {
return;
}
if (removeBOM(reader, UTF32BE)) {
return;
}
if (removeBOM(reader, UTF32LE)) {
return;
}
if (removeBOM(reader, UTF16BE)) {
return;
}
if (removeBOM(reader, UTF16LE)) {
return;
}
}
private static final int IO_BUFFER_SIZE = 4 * 1024;
public static Bitmap downloadBitmap(String url) {
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// Could provide a more explicit error message for IOException or IllegalStateException
getRequest.abort();
Log.w("ImageDownloader", "Error while retrieving bitmap from " + url +", "+ e.toString());
} finally {
if (client != null) {
client.close();
}
}
return null;
}
// http://apps-for-android.googlecode.com/svn/trunk/Panoramio/src/com/google/android/panoramio/BitmapUtils.java
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e("myapp", "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
// downsample your image to avoid OutOfMemory errors.
//http://stackoverflow.com/questions/2507898/how-to-pick-an-image-from-gallery-sd-card-for-my-app-in-android
/*
private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 140;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);
}
*/
public static Boolean saveBitmapToFile(Bitmap bitmap, File file) {
try {
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
final BufferedOutputStream bos = new BufferedOutputStream(fos, IO_BUFFER_SIZE);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bos);
bos.flush();
bos.close();
fos.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
}
return false;
}
/**
* Closes the specified stream.
*
* @param stream The stream to close.
*/
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
android.util.Log.e("myapp", "Could not close stream", e);
}
}
}
/**
* Copy the content of the input stream into the output stream, using a
* temporary byte array buffer whose size is defined by
* {@link #IO_BUFFER_SIZE}.
*
* @param in The input stream to copy from.
* @param out The output stream to copy to.
* @throws IOException If any error occurs during the copy.
*/
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
}
public static Bitmap downloadBitmap(String url) {
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// Could provide a more explicit error message for IOException or IllegalStateException
getRequest.abort();
Log.w("ImageDownloader", "Error while retrieving bitmap from " + url +", "+ e.toString());
} finally {
if (client != null) {
client.close();
}
}
return null;
}
// http://apps-for-android.googlecode.com/svn/trunk/Panoramio/src/com/google/android/panoramio/BitmapUtils.java
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e("myapp", "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
public static Boolean saveBitmapToFile(Bitmap bitmap, File file) {
try {
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
final BufferedOutputStream bos = new BufferedOutputStream(fos, IO_BUFFER_SIZE);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bos);
bos.flush();
bos.close();
fos.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
}
return false;
}
public static JSONArray getJSONArrayfromString(String data) {
try {
JSONArray a = new JSONArray(data);
return a;
} catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString()+". ");
return null;
}
}
public static JSONArray getJSONArrayfromURL(String url, List<NameValuePair> valuePairs) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String result = "";
try {
//HttpClient httpclient = new DefaultHttpClient();
//HttpPost httppost = new HttpPost(url);
//httppost.setEntity(new UrlEncodedFormEntity(valuePairs));
URL srv = new URL("" + url );
URLConnection connection = srv.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection;
InputStream is = httpConnection.getInputStream();
//BOMInputStream is = new BOMInputStream(httpConnection.getInputStream());
//HttpResponse response = httpclient.execute(httppost);
//HttpEntity entity = response.getEntity();
//InputStream is = entity.getContent();
//
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF8"),8);
removeBOM(reader);
//
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
//
JSONArray array = new JSONArray(result);
return array;
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString()+". "+result);
return null;
}
}
public static JSONObject getJSONfromURL(String url){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
//
String result = "";
try{
result = getStringfromURL(url, false);
}
catch (FileNotFoundException e){
return null;
}
// json parse
JSONObject res = null;
try{
res = new JSONObject(result);
return res;
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
catch (Exception e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return null;
}
public static String getStringfromURL(String url, boolean throwException)
throws FileNotFoundException
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String result = "";
try {
URL srv = new URL("" + url );
URLConnection connection = srv.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection;
InputStream is = httpConnection.getInputStream();
//
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF8"),8);
removeBOM(reader);
//
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e){
Log.e("error", "Error getting data from URL: "+e.toString());
if (throwException){
Log.e("error", "throw not found");
throw new FileNotFoundException();
}
return "";
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment