Android How to send text with accents to PHP - java

I have a problem with my app, when i try to send a text to my apache server which contains characters like má mé mí mó mú it sent the character as m?. How can i solve that?
This is my code:
public boolean loginstatus(String reporte, String user) {
File file = new File(fileUri.getPath());
try {
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
Log.e("enviando", "archivo "+fileUri.getPath());
Log.e("enviando", "reporte "+reporte);
Log.e("enviando", "usuario "+user);
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addTextBody("reporte", reporte);
entity.addTextBody("usuarioID",user);
if (file.length() <= 0){
}else{
entity.addPart("archivo", new FileBody(file));
}
final HttpEntity yourEntity = entity.build();
httppost.setEntity(yourEntity);
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}

First of all, the problem here is your encoding.
Either the database's table is not encoded to use UTF-8 or the String you send isnt.
table issue:
you can use CHARACTER SET utf8 on your db table.
String issue:
The elegant way to solve it is using
StringEntity entity = new StringEntity(Yourtext, "UTF-8");
The other way is to use your String's getBytes("UTF-8") function and use DataOutputStream

Related

How to decode text using Java?

I am getting a string in JSON response. It contains a dash (-), however instead of it, I get some special characters in the string.
I tried to decode it using UTF-8, but without success.
Here is that string:
String subject =
It contains – in the subject.
How to correctly decode it?
I am using the following Java code from which I get the JSON response:
try{
HttpGet httpGet = new HttpGet(WEB_SERVICE_URL);
String AUTHORIZATION_VALUE = "BEARER "+ "KEY"
httpGet.setHeader(AUTHORIZATION_KEY,AUTHORIZATION_VALUE);
String responseBody = "";
try(CloseableHttpResponse responseN = HttpClients.createDefault().execute(httpGet)){
responseBody = EntityUtils.toString(responseN.getEntity());
}catch (IOException e) {
e.printStackTrace();
}
JSONObject jsonObj = JSONFactoryUtil.createJSONObject(responseBody.toString());
jsonArray = jsonObj.getJSONArray("messages");
} catch (Exception e) {
e.printStackTrace();
}​
In json object, for one of the attribute I get encoded string as given below.
Thank you in advance!
UPDATE :-
I modified my code with following line,
responseBody = EntityUtils.toString(responseN.getEntity(), "utf-8");
But luck did not work. However string is replaced from – to –.
I referred few links to decode further this special character but I did not get success. Any help would be really appreciable. Thank you in advance !

Android application doesn't read entire HTTP response

I have written a web-service in Java. This web-service is hosted in TOMCAT. I am returning a JSON string. The JSON string is as follows:
accountDetailsNodes = [{mobileNumber=01948330292, errorMessage=null, customerCode=59744000002, photo=a string of 35536 charaters , accountOpenDate=null, errorFlag=N, customerNumber=4, customerName=Md. Saifur Hossain , accountID=2, accountTypeId=13, accountTypeDescription=Savings Account, customerPointId=1, balance=100000037640.50, accountTile=Md. Saifur Hossain}]
The length of the JSON string is 32613. But the full response is not coming to android apps. I think there may be some limitation on sending response from Tomcat. How can I overcome this limitation of Tomcat?
Updated:
This is my code to generate JSON.
try {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
JSONObject json = new JSONObject();
CashDepositDao dao = new CashDepositDao();
for (CashDepositModel bo : dao.getAccountDetals(accountNo,branchCode)) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("accountTile", bo.getAccountTitle());
map.put("accountOpenDate", bo.getAccountOpenDate());
map.put("mobileNumber", bo.getMobileNumber());
map.put("balance", bo.getBalance());
map.put("accountTypeId", bo.getAccountTypeID());
map.put("accountTypeDescription", bo.getAccountTypeDescription());
map.put("accountID", bo.getAccountID());
map.put("customerNumber", bo.getCustomerNumber());
map.put("customerCode", bo.getCustomerCode());
map.put("customerName", bo.getCustomerName());
map.put("customerPointId", bo.getCustomerPointID());
map.put("photo", bo.getPhoto());
map.put("errorMessage", bo.getErrorMessage());
map.put("errorFlag", bo.getErrorFlage());
list.add(map);
json.put("accountDetailsNodes", list);
}
System.out.println("accountDetailsNodes = " + list);
response.addHeader("Access-Control-Allow-Origin", "*");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(json.toString());
response.getWriter().flush();
// System.out.println("Response Completed... ");
} catch (Exception ex) {
Logger.getLogger(SourecAccountDetailsSV.class.getName()).log(Level.SEVERE, null, ex);
}
Sending And Getting response from Mobile App:
I am sending and getting the response using the following code:
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
System.out.println(json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
I have printed the string received in this method . Surprisingly, the full string is not received in this method.
How can I overcome this limitation of tomcat ?
Tomcat can send arbitrary length strings, and even if there was a limit, it wouldn't be measured in kilobytes but in orders of magnitude more. There is no tomcat limitation that you need to overcome. If your browser receives the full string, so can any other app.
As you're using json.toString() anyways, you could explicitly set the Content-Length header and see if this makes a difference. Stop worrying about Tomcat and double check if your Android App has some problems parsing a json response of this size, or if any network component in between limits your response in some way.
Edit: It's not Tomcat's problem, it's on the Android side and your answer is in the comments to the question.
The first problem is in what's proposed as "duplicate" question: You must not compare String with == as you do. Add else System.out.print("unexpected"); to your first if/else block to illustrate.
The second problem is that we have no clue where you get is from. As it looks now, it could be overridden by parallel requests (it's probably a class member?) - or due to the wrong string comparison never be initialized at all (leading to your problem that you can't see any content at all on the Android side, despite tomcat sending it). Make it a local variable, as proposed by EJP in his/her comment.
I think there may be some limitation on sending response from Tomcat.
There isn't.
How can I overcome this limitation of Tomcat?
There is no such limitation.
I am sending and getting the response using the following code:
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
Here you are incorrectly comparing strings. You should use equals(), not ==.
// ...
}else if(method == "GET"){
Ditto.
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
Here you are using is which may not have been initialized at all. It appears to be a member variable, so it is probably still null, so at this point I would expect a NullPointerException. is should of course be a local variable in this method.
I have printed the string received in this method. Surprisingly, the full string is not received in this method.
What is surprising is that anything is received, if that's what you're claiming. I would have expected an NPE.

Server cannot get binary data from Android app when using HttpPost

I use the following code to send binary data to CGI C++ program from Android app (it is called in doInBackground within AsyncTask):
public static HttpResponse makeRequestPost(String uri, MyObject obj) {
try {
HttpPost httpPost = new HttpPost(uri);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DataOutputStream dataStream = new DataOutputStream(stream);
obj.writeRawObject(dataStream);
byte[] byteArray = stream.toByteArray();
ByteArrayEntity entity = new ByteArrayEntity(byteArray);
entity.setContentType("application/octet-stream");
entity.setChunked(true);
httpPost.setEntity(entity);
return new DefaultHttpClient().execute(httpPost);
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "UnsupportedEncodingException. " + e.getMessage());
} catch (ClientProtocolException e) {
Log.e(TAG, "ClientProtocolException. " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException. " + e.getMessage());
}
return null;
}
I tested the same server using CURL with data written to a file using:
obj.writeRawObject(dataStream);
Also, both byteArray and entity variables in the code above contain correct data before calling execute(httpPost).
For some reason, on the server side
char* lenstr = getenv("CONTENT_LENGTH");
returns NULL when I run the app. Data I am trying to send are from a few bytes to 30 kB. It doesn't get them on the server side regardless the size. App can communicate with the server but do not attach a binary data. Is it something I am missing?
Something like this works from CURL:
curl -i -H "Content-Type:application/octet-stream" -X POST --data-binary #file_with_my_obj.bin <url>
Appreciate any ideas.
Can you try using binary/octet-stream instead of application/octet-stream in setContentType ?

Read body return from HttpResponse unstable in java?

I have a project need get livescores result over the internet. After research i have found that i can get livescore from http://iphone.livescore.com/iphone.dll?gmt=0.0 .
Then after that i write a simple application that get responded from the url above. But the problem is my code write to get result work unstable. Sometime it return body of the url not correct as the browser display, in my application it show unknow string with character that human can't readable.
Here my code, can some one can give me a advise?
private String getURLContent(String url) {
StringBuffer stringBuffer = new StringBuffer();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
InputStream inputStream = response.getEntity().getContent();
InputStreamReader reader = new InputStreamReader(inputStream,
"UTF-8");
int ch;
while ((ch = reader.read()) > -1) {
stringBuffer.append((char) ch);
}
reader.close();
}
} catch (ClientProtocolException e) {
log.fatal(e);
} catch (IOException e) {
log.fatal(e);
}
return stringBuffer.toString();
}
Make sure that the server sends data in UTF-8 format.
Beside this I would replace the read code with this one-liner:
EntityUtils.toString(response.getEntity(),"UTF-8");

How to call PHP function from Android?

I want to call specific php function on server and also to send some parameters.
Till now I achieved that I can open php file using HttpClient and executed data transfer to Json and show that in my app.
So, now I want to be able to call specific function and send parameter to it, how can I do that??
Sorry I didn't mansion that I need to call that function from Android.
here some code:
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/posloviPodaci/index.php");
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, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
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());
}
// Parsing data
JSONArray jArray;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
items = new String[jArray.length()];
for(int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
items[i] = json_data.getString("naziv");
}
} catch (Exception e) {
// TODO: handle exception
}
Thanks in advance,
Wolf.
If you are working with an MVC framework, such as CakePHP, you can simply create a route to a function that will output whatever JSON you'd like.
Otherwise,
You can utilize something simple at the top of your index.php such as this:
<?php
function foo($bar) { echo $bar; }
if(isset($_GET['action']) && (strlen($_GET['action']) > 0)) {
switch($_GET['action']) :
case 'whatever':
echo json_encode(array('some data'));
break;
case 'rah':
foo(htmlentities($_GET['bar']));
break;
endswitch;
exit; # stop execution.
}
?>
This will let you call the url with a parameter of action.
http://10.0.2.2/posloviPodaci/index.php?action=whatever
http://10.0.2.2/posloviPodaci/index.php?action=rah&bar=test
If you need to pass more sensitive data, I recommend you stick with $_POST and utilize some form of encryption.
You can handle that on php side. Create a Json object with a field called command and maybe a list of arguments.
On the php end after you decode the json just do:
if($obj.command == "foo"){
foo($obj.arg[0],$obj.arg[1]);
}

Categories

Resources