Display image in android with spaces in filename from online - android

I need to display an image in my android application. The problem is I want to get this image from somewhere online. The URL is like:
http://www.mydomain.com/hello world image.png
As you see the image name containing some spaces in it. Every time I execute my code this will show me exception of FileNotFound. and nothing happens.
Following is my code
String imagePathCon = "hello world image.png";
String imagePath = "http://www.mydomain.com/" + imagePathCon;
try {
URL url;
url = new URL(imagePath);
// url = new URL("http://www.azuma-kinba.com/wp-content/uploads/2012/05/Android-Make-Google-Loss-in-2010.png");
InputStream content = (InputStream)url.getContent();
Drawable d = Drawable.createFromStream(content , "src");
im.setImageDrawable(d);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I use to replace space with "+" but nothing happens.

This will work.
String imagePathCon = "hello world image.png";
imagePathCon=imagePathCon.replaceAll(" ", "%20");
String imagePath = "http://www.mydomain.com/" + imagePathCon;
You must know http://en.wikipedia.org/wiki/Percent-encoding#Character_data

plese use correct Url for getting image and use below code that would definetly help u...
replace space of URL using...
imagePath=imagePath.replaceAll(" ", "%20");
and now...
HttpGet httpRequest = new HttpGet(new URL(params[0]).toURI());
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpClient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream is = bufHttpEntity.getContent();
//image_value = new URL("image Url is here");
bm = BitmapFactory.decodeStream(new FlushedInputStream(is));
//imageLoader is object of iamge view
imageLoader.setImageBitmap(bm);

You need to url encode the path, like this:
String imagePathCon = URLEncoder.encode("hello world image.png", "UTF-8");

You can also use an http get request:
The simplest way is to simply call URLEncoder which will automatically replace all charaters in your string to the url encoded format.
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
HttpConnectionParams.setSoTimeout(httpParameters, 30000);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpGet httpGet = new HttpGet(URLEncoder.encode(url, "UTF-8"));
HttpResponse httpResponse = httpclient.execute(httpGet);
in = httpResponse.getEntity().getContent();
//Bitmap bmp = BitmapFactory.decodeStream(instream);
//create a bitmap or an image from the input stream

Related

Send Image and String by using MultipartEntity

I am working on an app that allows the user upload an image by using HttpPost method. I use MultipartEntity and therefore I added the libraries apache-mime4j-0.6.1.jar, httpclient-4.3.1.jar, httpcore-4.3.1.jar and httpmime-4.2.1.jar into my app. My upload code is like below:
public String uploadFile() throws Exception
{
String result = "";
try
{
HttpResponse response = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(_url);
request.setHeader("Accept", "application/json");
File file=new File(filePath);
String fileName=file.getName();
MultipartEntity imageEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName("UTF-8"));
imageEntity.addPart("imageName", new StringBody(fileName));
imageEntity.addPart("image", new FileBody(file, "application/octet-stream"));
request.setEntity(imageEntity);
response = httpClient.execute(request);
InputStream dataStream = response.getEntity().getContent();
BufferedReader dataReader = new BufferedReader(new InputStreamReader(dataStream));
String line = "";
while ((line = dataReader.readLine()) != null)
result+=line;
}
catch (Exception e)
{
}
return result;
}
I get response from my server but in my web service code Request.Files has no file. If I change the line:
MultipartEntity imageEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName("UTF-8"));
to
MultipartEntity imageEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
app is in process for a long time (about 3-4 minutes) and throws error. This is caused if I add an image. If I send only StringBody without FileBody, I get response from server and Request.Files in my webservice code return file count correctly. How can I fix this problem and upload image correctly? Any suggestion?

Can't display images from a URL [duplicate]

This question already has answers here:
Load image from url
(17 answers)
Closed 9 years ago.
With Android Studio I have a code that displays images from a direct URL.
I want that displays all the images from a site (they are item called <enclosure/>) and put that in my Custom ListView. So I get the String of the URLs where is present the image and then show it by the code below but I get nothing. Can you help me?
TextView txtImage = (TextView)rowView.findViewById(R.id.item_image);
txtImage.setText(web.get(position).getEnclosure());
txtImage.setTypeface(myTypeface);
ImageView img = (ImageView) rowView.findViewById(R.id.enclosure);
try {
URL url = new URL(context.getString(R.id.item_image));
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) {
}
This is all you need to do:
URL url = new URL("http://image10.bizrate-images.com/resize?sq=60&uid=2216744464");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);
It's not recommended to do this on the UI thread, as it blocks, but you can do it in an AsyncTask.

Spaces in URL creating issues in Android

I am downloading images from URL, but there are spaces in URL so its skipping thoses URL.
I have gone through several arcticles, which mentioned replace space with %20 or +, both the approach are not working. So what are the alternatives now.
Log.i("CountryFlagThumb", VArray.get(2).replaceAll(" ", "%20"));
http://id8lab.net/WorldNewsApp/flags/United Arab Emirates.png
Thanks
You don't encode the entire URL, only parts of it that come from "unreliable sources".
String data = URLEncoder.encode("United Arab Emirates.png", "utf-8");
String url = "http://id8lab.net/WorldNewsApp/flags/" + data;
You just Encode your url like
String url =Uri.encode("http://id8lab.net/WorldNewsApp/flags/United Arab Emirates.png")
Hope this will help.
To download image from url use the following,
HttpGet httpRequest = new HttpGet(URI.create(path) );
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
Bitmap bmp = BitmapFactory.decodeStream(bufHttpEntity.getContent());
httpRequest.abort();

Error using HTTP Post

I got an error using HttpPost for sending an MMS in Android.
In the Logcat it says:
ERROR/Here(447): ---------Error-----Target host must not be null, or set in parameters.
My sample code:
String url = "myurl";
HttpClient httpClient = new DefaultHttpClient();
try {
httpClient.getParams().setParameter(url, new Integer(90000)); // 90 second
HttpPost post = new HttpPost(url);
File SDCard = Environment.getExternalStorageDirectory();
File file = new File(SDCard, "1.png");
FileEntity entity;
entity = new FileEntity(file,"binary/octet-stream");
entity.setChunked(true);
post.setEntity(entity);
post.addHeader("Header", "UniqueName");
Log.i("MMSHTTP","----post---------------"+post);
HttpResponse response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
Log.e("Here",
"--------Error--------Response Status line code:" + response.getStatusLine());
}
else
{
// Here every thing is fine.
}
HttpEntity resEntity = response.getEntity();
if (resEntity == null) {
Log.e("Here","---------Error No Response!!-----");
}
} catch (Exception ex) {
Log.e("Here","---------Error-----"+ex.getMessage());
ex.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
How do I fix the error?
The url you're specifying is in your sample code is:
String url = "myurl";
In order for HttpClient to be able to determine the host name, you're going to need to supply a valid url. Something along the lines of:
String url = "http://myurl.com/index";
Note: The 'http://' is important so that the appropriate protocol can be determined.
This guy had the same problem.

Android - image upload sending no content

I've been looking into this for the last day or two and can not seem to find a solution to my issue. I am trying to post an image to a server using httppost.
I have tried two ways of doing this and both complete the post but with no content i.e. the content length is 0.
The first is as follows:
String url = "MYURL";
HttpClient httpClient = new DefaultHttpClient();
try {
httpClient.getParams().setParameter("http.socket.timeout", new Integer(90000)); // 90 second
HttpPost post = new HttpPost(url);
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot,"/DCIM/100MSDCF/DSC00004.jpg");
FileEntity entity;
entity = new FileEntity(file,"binary/octet-stream");
entity.setChunked(true);
post.setEntity(entity);
post.addHeader("Header", "UniqueName");
HttpResponse response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
Log.e("Here","--------Error--------Response Status line code:"+response.getStatusLine());
}else {
// Here every thing is fine.
}
HttpEntity resEntity = response.getEntity();
if (resEntity == null) {
Log.e("Here","---------Error No Response!!-----");
}
} catch (Exception ex) {
Log.e("Here","---------Error-----"+ex.getMessage());
ex.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
and the second is:
String url = "MYURL";
//File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(Environment.getExternalStorageDirectory(),"/DCIM/100MSDCF/DSC00004.jpg");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
// Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
Log.d("finishing", "The try catch function");
} catch (Exception e) {
// show error
}*/
As you can see I have hardcoded a path to a specific image, this is to be dynamic when I get it up and running.
Can anyone see what i'm doing wrong? Am I leaving out something? I know I use setChunked and setContenttype - is there a setContent option?
Any help would be grately appreciated.
Thanks,
jr83.
You can use upload your image by sending multipart messages; you might find this discussion useful.

Categories

Resources