Here is the link where I place a REST GET call.
http://adtouch.cloudfoundry.com/rest/ad/barcode/529a927973654526a309a77986062566/image
On opening it in browser, it redirects to other link and I get an image displayed.
I want to display this image on android. I am unable to determine what is the content I get by this call and how to convert it to an image to be displayed on android device.
This is the rest call I make:
HttpClient httpclient = new DefaultHttpClient();
String temp = "http://adtouch.cloudfoundry.com/rest/ad/barcode/529a927973654526a309a77986062566/image";
HttpGet request = new HttpGet(temp);
HttpResponse response = httpclient.execute(request);
ResponseHandler<String> handler = new BasicResponseHandler();
String result = httpclient.execute(request, handler);
System.out.println(result);
The result of this is numerous sequence of characters like:
(^( ?( ;QE??QE??ÊMÔâ1MT ??²¤i#íù¨ùhÙQ¶ê??m7Í¡?mFÏ#3|µu]¿Þ§+Uò?\°Ñ³Qçý?o?MiUWt?*¯÷?ª9Jæ·û´Ý¿59_åùi¬Õq$jE¨)ÿ??Á#D°?©ËÒªÆß7Þ«?õ q?/ÉR+Tr%F?¨(·LÙQ9]¨Ê´í?½;}??5???¨ßE??º?ôúc÷ ?·éGÍíFæZ??MK·ûÔè÷?Þ©<¥Û#Æ?ýÚ±üÕEJ7l O?Z³YêÄÒï¨ÕhK{}ë¹¾íZ?>U¨c}?RG#QGðüÍM2®>\·û´??í?l¨ÿ??xß«NUþón }Ênÿ??î9UR???nÖ?Å·ýÚo?¿Ä»¿Þ©(
I know how to set an image to the ImageView but the question is how to get an image from this call.
Look at the Javadoc for BitmapFactory. You must decode the stream in the HTTP response's entity:
InputStream in = client.execute(request).getEntity().getContent();
Bitmap bmp = BitmapFactory.decode(in);
in.close();
Note that network operations should not happen in the main thread. From your code it's not clear if you use an AsyncTask or not, however you should. Update the image in the onPostExecute() hook.
Related
I'm working/learning on an app for my store. The whole purpose of this app is to a customer can check recent flyer in the app.
How can I replace that image every week? how does update on app (like image change) works? Does customer need to update the app in order to see new image? or is there any way where my app will fetch photo from "XYZ" location online, and all I have to do is upload that image online to "XYZ" location.
I suggest showing your weekly image from a URL like this
ImageView img = (ImageView) findViewById(R.id.imageView1);
try {
URL url = new URL("http://web.yourcompany.com/weekly.jpg");
HttpGet httpRequest = null;
httpRequest = new HttpGet(url.toURI());
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
InputStream input = b_entity.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(input);
img.setImageBitmap(bitmap);
} catch (Exception ex) {
}
or using the WebView to load the image from URL.
WebView web = (WebView) findViewById(R.id.webView1);
web.loadUrl("Your/Url.jpg");
Ideally, you want to call this code from a separate thread.
This is the code I'm using.
String imageURL;
Bitmap bitmap = null;
imageURL = "http://graph.facebook.com/" + fbID + "/picture?type=";
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(imageURL)
.getContent());
} catch (Exception e) {
e.printStackTrace();
}
when i use this URL in browser it shows image, but when trying to get it in bitmap it gives null.
I've checked many question, but nothing help me.
This code works for me with HTTPGet:
HttpGet httpRequest = new HttpGet(URI.create(linkUrl) );
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
bmap = BitmapFactory.decodeStream(bufHttpEntity.getContent());
httpRequest.abort();
This problem is due to the fact that, Facebook uses its graph API url merely as a redirection endpoint. If you copy paste a facebook profile picture URL such as
http://graph.facebook.com/subinsebastien/picture
What actually happens is that, Facebook redirects you to the actual image URL. Thus, when you try to open an input stream with the graph API url, you wont actually get a bitmap, rather a redirect response is what you get. In my case, this is where I'm being redirected to.
https://scontent-b.xx.fbcdn.net/hprofile-prn1/l/t5.0-1/48771_100000333400619_475851971_q.jpg
Thus, I would rather suggest you to use an actual HTTPGet to get the bitmap first.
how to read dynamically image from web in android, i have a method which takes String type url and return drawable, i want to get an image from remote location and set it in my imageview and through remote location change to image occur and these change automatically reflect in my android application.
i have this code, any help will be appreciable, and thanks in advance
public static Drawable LoadImageFromWeb(String url){
try{
InputStream is = (InputStream) new URL(url).getContent();
Drawable drw = Drawable.createFromPath(url2);
//Drawable draw = Drawable.createFromStream(is, url2);
return drw;
}catch(Exception ex){
ex.printStackTrace();
return null;
}
thanks.
You could use an external library like Picasso or Universal-Image-Loader. URLS:
http://square.github.io/picasso/
https://github.com/nostra13/Android-Universal-Image-Loader
Use the bellow http network connection in Asynctask or a thrad.
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 20000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 30000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost(url);
//Adding the parameter values (if required input to remote service)
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair(Constants.URL_PARAM_PROVIDERID,Utilities.getProviderID(PageCurlGraph.this)));
nameValuePairs.add(new BasicNameValuePair("requestedDate",params[i]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
InputStream instream = httpEntity.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(instream);
gm = new GraphModel();
gm.setBitmap(bitmap);
your code is a bad way to showing an remote image from url. it can caused your apps not responsive.
i recommend you to using some 'image loader library' which it is take the advantages of android asynchronous task and keep your apps responsive.
for example, you can use this library:
https://github.com/androidquery/androidquery/releases/tag/0.26.8
all you need to do is import the library into your project, then load your image in just a view code:
ImageView imgView = (ImageView) findViewById(R.id.imageview);
AQuery aq = new AQuery(this); // assume you are doing this inside activity
String someImageURL = "http://someurl.com/someimage.jpg";
aq.id(imgView).image(someImageURL, true, true); // see documentation for detail
if u don't want to use tool or image loader library and your application not interacting to internet continuously, Then
you can take XML from server at ones, that containing image url's list, parse the XML, and download them one by one on sd card and show them offline by using ImageView.setImageResource(...) this process will make your app more faster and you can set time interval to check update from server.
If u have large no of images then u have to use image loader library because above process may cause memory space issue on device .
I'm currently working on an app that requires images to be passed to and from an App engine back-end. Originally I planned on sending the images (they are only small - max 100kb - average 20kb) directly through the endpoint however when sending the data as a byte array through the endpoint I receive a JSON error (from the rest API) stating that the data has an invalid character. Is there a way around this?
My second attempt was to use use the BlobService and return an upload URL to the client using the below code:
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
UploadOptions uploadOptions = UploadOptions.Builder.withGoogleStorageBucketName("bucketname").maxUploadSizeBytes(1048576);
String url = blobstoreService.createUploadUrl("/uploaded", uploadOptions);
Then using a HTTP post on the android device to upload the image:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("data", new ByteArrayBody(data,"image/png","img.png"));
httppost.setEntity(entity);
String res = EntityUtils.toString( httpclient.execute(httppost).getEntity(), "UTF-8");
This seems to work and the image is uploaded. However, I have no idea how to get the blobkey of this uploaded image. Does anyone know? Also, the result from the HTTP post is a 404 error - because the "/uploaded" page does not exist I'm guessing?
Thirdly, when manually typing in the blobkey and using it to return and image serving url with this code:
private String getImage(){
return getThumbUrl(new BlobKey("encoded_gs_key:ZGNpbWcxMy93czZwZ2lUeXdpY0xvZ2xtZGpHZ2dn"));
}
private String getThumbUrl(BlobKey blobkey){
ServingUrlOptions options = ServingUrlOptions.Builder.withBlobKey(blobkey);
try {
return ImagesServiceFactory.getImagesService().getServingUrl(options);
} catch(IllegalArgumentException e) {
e.printStackTrace();
return null;
} catch(ImagesServiceFailureException e) {
e.printStackTrace();
return null;
}
}
I receive the URL of the image however the image colors are all messed up. I am uploading indexed pngs... I'm not sure if the ImageService can handle them correctly. If it cant, how do I go about serving the image directly i.e. not through the ImageService but through BlobstoreService.serve()?
Here is an image of the resultant picture from the ImageService URL: http://i.imgur.com/EhfkJ9j.png
Cheers,
Ben
About the blob key, when you create the upload url you pass a paramenter with the name of your appengine page that gets called after upload. You need to implement that page ("uploaded") https://developers.google.com/appengine/docs/java/blobstore/#Java_Uploading_a_blob
I'm invoking a rest WS that returns XML. Some elements have strings include special characters like áãç etc...
When I get the information via browser all of it is shown properly but when invoking it from Android I don't get the proper special characters.
Notice the 'decoded' and 'encoded' variables:
when I use
URLDecoder.decode(result, "UTF-8")
The result stays the same
when I use
URLEncoder.encode(result, "UTF-8") The result changes to what it would be expected (full of %'s symbols and numeric representing symbols and special characters).
Here's the method to call the webservice:
public void updateDatabaseFromWebservice(){
// get data from webservice
Log.i(TAG, "Obtaining categories from webservice");
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(ConnectionProperties.CATEGORIES_URI);
ResponseHandler<String> handler = new BasicResponseHandler();
String result = "";
String decoded;
String encoded;
try {
result = client.execute(request, handler);
decoded = URLDecoder.decode(result, "UTF-8");
encoded = URLEncoder.encode(result, "UTF-8");
String c = "AS";
} catch (Exception e) {
Log.e(TAG, "An error occurred while obtaining categories", e);
}
client.getConnectionManager().shutdown();
}
Any help would be appreciated
Use this to get xml string, assuming the server encodes data in UTF-8:
HttpResponse response = client.execute(request);
... // probably some other code to check for HTTP response status code
HttpEntity responseEntity = response.getEntity();
String xml = EntityUtils.toString(responseEntity, HTTP.UTF_8);
Uh. URLDecoder and encoder are for encoding and decoding URLs, not XML content. It is used for URL you use when making requests. So code is just... wrong.
But even bigger issue is that you are taking a String, whereas content is really XML which needs to be parsed. And for parser to do proper decoding of UTF-8 (and handling of entities etc), you would be better of getting a byte[] from request, passing that to parser; although asking http client to do decoding may work ok (assuming service correctly indicates encoding used; not all do -- but even if not, XML parsers can figure it out from xml declaration).
So: remove URLDecoder/URLEncoder stuff, parser XML, and extract data you want from XML.