How to send Emoji Icons on php server with Multipart Entity - android

I am working on a project in which I am using this library https://github.com/ankushsachdeva/emojicon. I am able to see the Emoji Keyboard but when I am sending the text from Editext which contains Emoji Icons they are converted into ??
After some research I found out this solution Post UTF-8 encoded data to server loses certain characters
By using this
form = new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
the problem get solved. But I have to use MultipartEntity to send images also to server.
When I set Encoding in MultiPartEntity like below:
MultiPartEntity entity = new MultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
null, Charset.forName("UTF-8"), new MultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
}
});
It is not working here, how can achieve the same with MultipartEntity. Please help me.

Related

Sending a post in android with bad encoding

I'm sending post content to a server from android.
The problem is that the data at the server arrives wrong, with encoding problems, for example "{" arrives as "%7B%".
This is the code from android:
RequestParams params = new RequestParams();
params.put("alta", "{s}");
String ruta = "http://www.something.com/receive";
client.post(ruta, params,
new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
}
}
The server part is just receiving this data, like:
$data = $this->request->data;
$data =file_get_contents('php://input');
This issue is not directly related to text encoding per se.
As can be seen from the docs for RequestParams, text values are directly included in the url. As all text that is included in URLs has to be encoded to only include characters that are allowed in URLs (ASCII), text is url encoded.
AsyncHttpClient automatically does that encoding in the background, so you receive the strings in encoded form on the php side.
In order to get the original text you sent, you can use the rawurldecode() or urldecode() function on the php side to decode the encoded string you receive.
You need to use URLEncoder.encode(...) the the data part of you request.
At the server URL decode it.
You should be fine.

How to upload images from Android Sqlite to Local server folder using json

Am Having Images and Text in android Sqlite database.and My Need is to uplaod those images and text to my system folder via Local Server using Json..I dont have any idea , Please help me anyone by giving ideas and coding or example .. I googled this topic ..Most of all link based on Php Server only ..Thanks in Advance if anyone help me..
You cannot simple put your text and images directly on server from you app. You need to have Server side logic to handle the requests. While searching, you must have found lot of PHP server side code, because PHP is the easiest to get started.
The only way i could think of to send images along with text in JSON format is to convert images to Base64. On the server side, you have to convert them back to images and save.
Also, don't save images directly in Sqlite database. It's not designed to handle large BLOB's (images or any other binary data). You can save the images to file system and save the paths in database.
Edit:
You can use the following code to send JSON string from Android to PHP
on Android
JSONObject jsonObject = new JSONObject();
jsonObject.put("text", "YOUR_TEXT_HERE");
jsonObject.put("image", "YOUR_BASE64_IMAGE_HERE");
StringEntity postBody = new StringEntity(jsonObject.toString());
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://YOUR_URL_HERE");
httpPost.setEntity(postBody);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpClient.execute(httpPost);
PHP code
$raw_json_string = file_get_contents('file://input');
$json = json_decode($raw_json_string);
// Copied shamelessly from: http://stackoverflow.com/a/15153931/815540
function base64_to_jpeg($base64_string, $output_file) {
$ifp = fopen($output_file, "wb");
$data = explode(',', $base64_string);
fwrite($ifp, base64_decode($data[1]));
fclose($ifp);
return $output_file;
}
$text = $json->text;
$base64_image = $json->image;
base64_to_jpeg($base64_image, 'PATH_YOU_WANT_TO_SAVE_IMAGE_ON_SERVER');
That's all there is to it....!
haven't tested the code though

How to set character encoding of httpclient

I am using this httpclient: http://loopj.com/android-async-http/
I am getting a json with this httpclient.
I want to set character enconding of this httpclient. The JSONObject that the client returns contains turkish chars such as şğöü. But it is corrupted and i cant view this characters.
How can i set character encoding of this httpclient?
The correct would be that server provides the encoding of the returned page.
If it does that you will receive the correct one.
But if it doesn't provides the encoding Async-http seems to assume UTF-8 and looking at the code it doesn't seems to support providing a default alternative one.
Relevant code in AsyncHttpResponseHandler :
// Interface to AsyncHttpRequest
void sendResponseMessage(HttpResponse response) {
...
responseBody = EntityUtils.toString(entity, "UTF-8");
If you want to do you will need to user your own version of AsyncHttpResponseHandler or suggest a patch to be able to specify default encoding.
i resolved this problem by modifying the loopj source code file "AsyncHttpResponseHandler.java"...
void sendResponseMessage(HttpResponse response){
.........
//responseBody = EntityUtils.toString(entity, "UTF-8");
responseBody = EntityUtils.toString(entity, "ISO-8859-1");
}
ISO-8859-1 encoding will give you the correct characters..

Consuming Web service from Android Application

I am a beginner on Android app development. I want to confirm if my approach is correct and as per best practices in Android world.
I have an android application that needs textual data (no graphic, video). The data comes from REST based web service as JSON string. I consume this web service using HttpGet object, parse json string using JSONArray and display data.
All this happens in a button click.
My questions are:
Is there a better (or android-style) approach to do the same?
What is the preferred approach to retrieve and post graphic contents to REST based web service?
Any help is most appreciated.
Thanks
Please find my inline commnets,
All this happens in a button click.
My questions are:
Is there a better (or android-style) approach to do the same?
Ideal approach to trigger the Webservice calls in Async task or in a service, so your UI thread will not be blocked till HTTP fires and get the response.
What is the preferred approach to retrieve and post graphic contents to REST based web service?
The graphics content will be usually base64 when you try to retrieve it from the backend.
Refer this example : http://androidtrainningcenter.blogspot.in/2012/03/how-to-convert-string-to-bitmap-and.html
for the posting the graphics to the server
I'm going to assume that you know the path and filename of the image that you want to upload. Add this string to your NameValuePair using image as the key-name.
Sending images can be done using the HttpComponents libraries. Download the latest HttpClient (currently 4.0.1) binary with dependencies package and copy apache-mime4j-0.6.jar and httpmime-4.0.1.jar to your project and add them to your Java build path.
You will need to add the following imports to your class.
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
Now you can create a MultipartEntity to attach an image to your POST request. The following code shows an example of how to do this:
public void post(String url, List nameValuePairs) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int index=0; index < nameValuePairs.size(); index++) {
if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue())));
} else {
// Normal string data
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
} catch (IOException e) {
e.printStackTrace();
}
}
Hope this helps!
Hey refer this link which will train you better in parsing json data as you required in Android App. Loading the graphic required some lazy loading mechanism which you can refer it from here.

Programmatically filling in a website form using MultipartEntity

I'm taking a mobile development class, which focuses on Android, and for my term project I thought it would be cool if I made a little application that returns a list of cancer-related events and fundraisers. Basically what I have to do is programmatically fill in a webform given criteria that is input from my application, and parse the returned results to give a list of events, because for some reason the American Cancer Society doesn't keep a public list of all events. This is my first real experience with android, and I have almost zero experience with network programming. If I really wanted to, I could just change the URL I go to based on the paramaters given to me, because the ACS event search URLs all look almost exactly the same, but I want to do it "right". I looked at this post and this one for guidance, which led me to the MultipartEntity. They've been very helpful, but I really am not sure what to do next. Code is below:
//Base case, creates entity based on Entered ZIP Code
public void sendRequest()
{
EditText MyEditText = (EditText)findViewById(R.id.zip_edit_text);
String ZIP = MyEditText.getText().toString();
HttpClient defaultClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.cancer.org/Involved/Participate/app/event-search");
try{
MultipartEntity entity = new MultipartEntity();
entity.addPart("ZIP",new StringBody(ZIP));
httppost.setEntity(entity);
HttpResponse response = defaultClient.execute(httppost);
HttpEntity result = response.getEntity();
InputStream stream = result.getContent();
String s = new Scanner(stream).useDelimiter("\\A").next();
Intent intent = new Intent(HomeScreen.this, ListResults.class);
startActivity(intent);
AlertDialog dialog = new AlertDialog.Builder(this).create();
dialog.setMessage(s);
dialog.show();
}catch (ClientProtocolException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
It's pretty bare-bones right now, as you can see. The AlertDialog is used just to see what the HttpResponse looks like, and it seems like it does the POST correctly, and the ZIP code ends up in the right text field, but it doesn't actually "click" the search button. Personally, I think either:
1.) My HttpPost object's URL was incorrect
2.) I used POST instead of GET, or i should POST then GET
I really have tried to work this out myself, and have searched StackOverflow, but I've really come to a rough patch, and as I said before, my network programming experience is near nonexistent. Any help would be appreciated.
I would suggest that you do a printout the URL that was sent through your multipart method, do a search via the web browser, and see if both URL matches. If the URL doesn't match, it means that there's something wrong while setting your entity, etc.

Categories

Resources