Spaces in URL creating issues in Android - 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();

Related

How to get Bitmap from URL that redirect to https URL

Hello I am trying to get Bitmap from URL, Here this URL is redirecting to the another https URL.
URL : http://graph.facebook.com/244054592454345/picture
I am trying to get bitmap like below but this is not working for me, tried this Android : Getting a Bitmap from a url connection (graph.facebook.com) that redirects to another url but not worked for me.
Using below code, I am always getting null in the bitmap.
URL imgUrl = new URL("http://graph.facebook.com/{user-id}/picture?type=large");
InputStream in = (InputStream) imgUrl.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(in);
Any idea to get bitmap from a link which redirect to another as like me ?
This below code solved my problem and working fine.
URL fbAvatarUrl = new URL("http://graph.facebook.com/"+userProfileModel.getFacebookID()+"/picture");
HttpGet httpRequest = new HttpGet(fbAvatarUrl.toString());
DefaultHttpClient httpclient = HttpClient.getInstance();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
Bitmap fbAvatarBitmap = BitmapFactory.decodeStream(bufHttpEntity.getContent());
httpRequest.abort();

Display image in android with spaces in filename from online

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

What is the best way to send a name value pair to a server?

I've been trying this for the best part of two weeks now, and I am really stuck. Initially I had created a simple ObjectOutputStream client - server program - with the client being the Android app, but it does not work (it reads the connection but not the object).
So now I am confused as to what other approaches I might be able to take to carry out this simple task? Can anyone Help?
have you tried URLConnection using post method? :)
Or get method like:
String yourURL = "www.yourwebserver.com?value1=one&value2=two";
URL url = new URL(yourURL);
URLConnection connection = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
response = in.readLine();
you can try JSON stirng to send data. We have a lot of stuff available on how to work with JSON and also there are many api's. JSONSimple is the one I can suggest. Its really easy.
why don't you try this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
You can use this to post an Entity to server:
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(url);
postRequest.setEntity(entity);
try {
HttpResponse response = httpClient.execute(postRequest
);
String jsonString = EntityUtils.toString(response
.getEntity());
Log.v(ProgramConstants.TAG, "after uploading file "
+ jsonString);
return jsonString;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
An Entity can be name value pair:
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("key1", value1));
nvps.add(new BasicNameValuePair("key2", value2));
Entity entity=new UrlEncodedFormEntity(nvps, HTTP.UTF_8)
Or you can send an entity with bytearray.
Bitmap bitmapOrg=getBitmapResource();
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] data = bao.toByteArray();
MultipartEntity entity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE)
entity.addPart("file", new ByteArrayBody(data, "image/jpeg",
"file"));
If you want to post json to server:
Please check out this link How do I send JSon as BODY In a POST request to server from an Android application?
For serializing and deserializing java object, I recommend https://sites.google.com/site/gson/gson-user-guide#TOC-Using-Gson
Really hope it can help you see an overview of sending data to server

Getting data from web service from android

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(address));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
When I retrieve information like that, bufferedreader in contains only one long line with the whole text. It doesn't divide break data into lines. As a result, only first 3 kwords are fit into the line and the rest is losed. How can I avoid this problem?
Simply
URL url = new URI(address).toURL();
InputStream is = url.openStream();
Have you try this?
String data = EntityUtils.toString(response.getEntity());

How can I read a bytearray from an HttpResponse?

I'm making an http connection using following code:
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response = client.execute(httpPost);
I want to read a bytearray from the response object.
How would I do that?
You can read the byte array directly with the method: EntityUtils.toByteArray
Example
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("localhost:8080/myurl");
HttpResponse response = client.execute(get);
byte[] content = EntityUtils.toByteArray(response.getEntity());
You can use:
HttpResponse response = client.execute(httpPost);
String content = EntityUtils.toString(response.getEntity());
byte[] bytes = content.getBytes("UTF8");
You can replace the character encoding with one appropriate for the response.
I did something very similar to this, but it was a while ago.
Looking at my source code I used
HttpClient client = new DefaultHttpClient();
String url = "http://192.168.1.69:8888/sdroidmarshal";
HttpGet getRequest = new HttpGet(url);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String proto = client.execute(getRequest, responseHandler);
I'm pretty certain that the ResponseHandler is the key to this. My get request simply returned something I needed as a string, which was quite simple.
In the case of a bytearray you'll probably want to use an InputStream like so
ResponseHandler<InputStream> responseHandler = new BasicResponseHandler();
InputStream in = client.execute(getRequest, responseHandler);
After which just handle the InputStream as normal.
A bit of googling suggested you may also need to use HttpResponseHandler() rather than BasicResponseHandler() as in my example, I'd fiddle.
The full source code of my work is here, it might be helpful for you.
Kotlin Way
run this on async task on background thread otherwise it will through the error that network task is running on main thread
doAsync {
val client: HttpClient = DefaultHttpClient()
val get = HttpPost("*your url*")
get.setHeader("Authorization","Bearer "+Utils.token)
val response: HttpResponse = client.execute(get)
val content = EntityUtils.toByteArray(response.getEntity())
onComplete {
createPdf(content)
}
}

Categories

Resources