ambiguous behavior of new line character - android

I am uploading a large string to web-service. The string contains new line character which is written as "\n".
The data looks some thing like:
05/06/2012 11:35:43 AM- DB exists, transferring data\n05/06/2012
11:48:20 AM- loadUserSpinners, cursor.getCount()=2\n05/06/2012
11:48:20 AM- Battery: 50%\n05/06/2012 11:48:20 AM- ITEM SELECTED: 0
the above data is stored in string JsonArrObj. To upload the data/string, i am using the following code:
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 360000; //6 minutes
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 420000; //7 minutes
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
JSONArray jsonParams = new JSONArray();
Object[] params={IPAddress,Database,DbName,DbPassword,JsonArrObj};
for (int i = 0; i < params.length; i++) {
jsonParams.put(params[i]);
}
JSONObject jsonRequest = new JSONObject();
jsonRequest.put("id", Id);
jsonRequest.put("method", FunctionName);
jsonRequest.put("params", jsonParams);
JSONEntity entity = new JSONEntity(jsonRequest);
entity.setContentType("application/json; charset=utf-8");
HttpPost request = new HttpPost(URL);
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity httpEntity = response.getEntity();
InputStream content = httpEntity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content,"iso-8859-1"),8);
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
LogE("result line: "+line);
String str=convertString(line);
parseJson(str);
}
content.close();
}
The string is uploaded successfully. The problem I am facing is: while string is being converted to jsonParams, the "\n" in the string data gets converted to "\\n" as a result, on the server side, it shows a small box in stead of new line.
When I open this string in NOTEPAD application, it displays small boxes. But when I open it in WORDPAD app, text is displayed on a new line. According to me, I might have entered in-correct "content-type" or encoding. Please suggest a solution for the same.
JsonArrObj= URLEncoder.encode(JsonArrObj, "utf-8"); gave error while uploading itself...
The data which is sent in the jsonParams- jsonArrObj finally looks like:
05\/06\/2012 04:05:52 PM- DB exists, transferring
data\\n05\/06\/2012 04:32:56 PM- loadUserSpinners,
cursor.getCount()\\u003d2\\n05\/06\/2012 04:32:56 PM- Battery:
50%\\n05\/06\/2012 04:32:56 PM- ITEM SELECTED: 0

Well, the encoder escapes your newline characters. If you want to transport newline chars properly, you can encode the whole stream with base64. If your target os (for data to send) is Windows then you should use \r\n, if mac then \r if unix\linux then \n. After encoding data try to send the encoded and decode it on the other side. For base64 Mr. Google will convince you.

Hey why don't you use the Unicode values for \n as and any other character that is creating this problem
like this U+002FU+006E

Related

Android - Get number from text file online and compare

Totally new here, at least, first post.
What I'm trying to accomplish is that the code reads a number from a text file on my webserver, and it compares with an other inbuild number. When the number from online is bigger, it will do something. I've tried many codes, but none of them are working, so I don't have an example either.
Can somebody help me with this?
you can Use the-
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new
HttpGet("http://www.urlOfThePageYouWantToRead.nl/text.txt");
HttpResponse response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line + "\n");
}
TextView.setText(total)
;
now this number must be in total variable. now convert that string number into integer as
int number = Integer.parseInt(total);
now you can compare this number with your mynumber as=
if(number>mynumber)
{ //do stuff

Sending an Image to a server to create Blob key in android

I want to send an image captured by camera to a server, which creates blob key. I am not getting how to send that image to the server. In which format is the image is sent?
I am trying to send parameters through HttpParams.
This is my code but the data is not going to server. What is the problem?
String name=tname.getText().toString();
String addr=taddr.getText().toString();
String age=tage.getText().toString();
String cnct=tcnct.getText().toString();
String gen=tgen.getText().toString();
String wtm=twtm.getText().toString();
ba1=Base64.encodeToString(imageform, 0);
Date d=new Date();
String date=d.toString();
InputStream i1;
String back="";
HttpParams p=new BasicHttpParams();
p.setParameter("vname",name);
p.setParameter("address", addr);
p.setParameter("age", age);
p.setParameter("contact", cnct);
p.setParameter("gender", gen);
p.setParameter("whomto", wtm);
p.setParameter("myFile", ba1);
try {
HttpClient httpclient = new DefaultHttpClient(p);
HttpPost res=new HttpPost(result);
HttpResponse response = httpclient.execute(res);
HttpEntity entity = response.getEntity();
i1 = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(i1,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
if ( reader.readLine() == null) {
Log.e("inside if","No data");
} else {
String line = reader.readLine();
i1.close();
back=sb.toString();
}
I am not getting any errors or exceptions.
You should make an MultipartPost and add the file to your MultipartEntity as follows :
multipartEntity.addPart("data", new FileBody(capturedImagePath));
You should have a look a this answer Multipart post with Android for a more detailed answer.
Encode the image, using Base64, to a String and send it using MultipartEntity.
In php retrieve the string an unpack it with base64_decode to the image.
Check this question:
https://stackoverflow.com/questions/10145417/android-send-image-through-http-post

Huge HttpPost response : JSON

I am sending an HttpPost request and getting the response in JSON format. But, as the response is so huge, I receive only a small part of the response compared to what I can see it in the browser. My code is below:
StringBuilder builder = new StringBuilder();
HttpPost httpPost = new HttpPost(uri);
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
As the default buffer size is 8192 characters. I just tried with giving more value but it didn't matter. So, any suggestions on this...
I think that +Che Jami is onto something in the OP.
Manjunath, logcat will only output 1024 characters at a time. Have you tried outputting the String builder 1024 characters at a time? Did you check the length of the string after reading into it?
Send only chunks (batches) of your full response in your responses and while your response is not finished use polling.

How to send a JSON object over POST Request with Android

I am trying to build a small application in which the application will communicate with a php script with the help of JSON objects. I successfully implemented the GET Request test application but using JSON with post is creating problems. The code generates no error but my php script reply with no nothing except an empty Array() which implies that nothing was sent over the connection with code:
<?php print_r($_REQUEST); ?>
and trying with
<?php print($_REQUEST['json']); ?>
throws HTML back to the application with json variable not found error.
I have already tried a few solutions mentioned here including: How to send a JSON object over Request with Android? and How to send a json object over httpclient request with android so it would be great if you can point out my mistake and can briefly describe what exactly I was doing wrong. Thanks.
Here is the code snippet for from where the JSON Object is converted into string and then attached to a Post variable.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppostreq = new HttpPost(wurl);
StringEntity se = new StringEntity(jsonobj.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppostreq.setEntity(se);
//httppostreq.setHeader("Accept", "application/json");
//httppostreq.setHeader("Content-type", "application/json");
//httppostreq.setHeader("User-Agent", "android");
HttpResponse httpresponse = httpclient.execute(httppostreq);
HttpEntity resultentity = httpresponse.getEntity();
Here is TCP Stream Dump collected through wireshark if it can help:
POST /testmysql.php?test=true HTTP/1.1
Content-Length: 130
Content-Type: application/json;charset=UTF-8
Content-Type: application/json;charset=UTF-8
Host: 192.168.100.4
Connection: Keep-Alive
User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.4)
{"weburl":"hashincludetechnology.com","header":{"devicemodel":"GT-I9100","deviceVersion":"2.3.6","language":"eng"},"key":"value"}HTTP/1.1 200 OK
Date: Mon, 30 Apr 2012 22:43:10 GMT
Server: Apache/2.2.17 (Win32)
Content-Length: 34
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html
Array
(
[test] => true
)
Test // echo statement left intentionally.
you are using PHP on the server side, so your HTTP entity must be a multipart encoded one. See this link. You are using a string entity, but this is not correct. It must be a MultipartEntity, which emulates what the browser does when you submit a form in a web page. MultipartEntity should be in httpmime jar.
Once you have your multipart entity, simply add a Part named "json", and set its contents to the string representation of your json-encoded object.
Note that this answer is because you use PHP on the server side, so you must use its "protocol" to read variables via $_REQUEST. If you used your own request parser oh the server side, even a StringEntity could be ok. See HTTP_RAW_POST_DATA
The below should work. Make sure to set the appropriate keys for what your form post is expecting at the top. Also I included how to send an image as well as other various json data, just delete those lines if that is not necessary.
static private String postToServerHelper(
String action,
JSONObject jsonData,
byte[] imageData){
// keys for sending to server
/** The key for the data to post to server */
final String KEY_DATA = "data";
/** The key for the action to take on server */
final String KEY_ACTION = "action";
/** The return code for a successful sync with server */
final int GOOD_RETURN_CODE = 200;
/** The key for posting the image data */
final String KEY_IMAGE = "imageData";
/** The image type */
final String FILE_TYPE = "image/jpeg";
/** The encoding type of form data */
final Charset ENCODING_TYPE = Charset.forName("UTF-8");
// the file "name"
String fileName = "yourFileNameHere";
// initialize result string
String result = "";
// initialize http client and post to correct page
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.yourdomain.com/yourpage.php");
// set to not open tcp connection
httpPost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
// build the values to post, the action and the form data, and file data (if any)
MultipartEntity multipartEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
try{
multipartEntity.addPart(KEY_ACTION, new StringBody(action, ENCODING_TYPE));
multipartEntity.addPart(KEY_DATA, new StringBody(jsonData.toString(), ENCODING_TYPE));
if (imageData != null){
multipartEntity.addPart(KEY_IMAGE, new ByteArrayBody(imageData, FILE_TYPE, fileName));
}
}catch (Exception e){
return e.getMessage();
}
// set the values to the post
httpPost.setEntity(multipartEntity);
int statusCode= -1;
// send post
try {
// actual send
HttpResponse response = client.execute(httpPost);
// check what kind of return
StatusLine statusLine = response.getStatusLine();
statusCode = statusLine.getStatusCode();
// good return
if (statusCode == GOOD_RETURN_CODE) {
// read return
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
content.close();
result = builder.toString();
// bad return
} else {
return String.parse(statusCode);
}
// different failures
} catch (ClientProtocolException e) {
return e.getMessage();
} catch (IOException e) {
return e.getMessage();
}
// return the result
return result;
}
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
JSONObject clientList = new JSONObject ();
clientList.put("name","");
clientList.put("email","");
clientList.put("status","");
clientList.put("page","");
JSONObject listclient = new JSONObject ();
listclient.put("mydetail", clientList);
//--List nameValuePairs = new ArrayList(1);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("token", tokenid));
nameValuePairs.add(new BasicNameValuePair("json_data", listclient.toString()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.d("JSON",nameValuePairs.toString());
//-- Storing Response
HttpResponse httpResponse = httpClient.execute(httpPost);

Setting TextView's text as non-English text received from JSON response

I'm getting back names of (Foursquare) venues from a server call where the names of the venues returned can be in English or non-English.
Assume the venue name is in a JSON object as follows:
{...
"name":"venue name which can be in any language"
...}
I'm creating a JSONObject from this response and then pulling out the name of the venue as follows:
String name = jsonObject.getString("name");
Lastly, I'm setting the TextView's text to show the name of the venue as follows:
myTextView.setText(name);
I'm finding however for Arabic names that where the Arabic characters are joined in the original JSON object (as they should be), the characters that show in the app (i.e. in the TextView) are disjoint. (I'm not too familiar with other languages so can't really tell if they're showing incorrectly too.)
Is there something additional I should be doing to pull out non-English names correctly from the JSON object and setting it as the text of a TextView, or is it down to the phone to decide how the text will be displayed?
Edit: I've tried parsing the server response (as suggested by #bbedward) explicitly specifying the content encoding as UTF-8 as follows...
HttpEntity httpEntity = httpResponse.getEntity();
String responseMessage = EntityUtils.toString(myHttpEntity, "UTF-8");
JSONObject jsonObject = new JSONObject(responseMessage);
... but still no joy. (Arabic characters appear, as before, disjoint in words where they should be joint up.) Could it be a phone thing or is there something extra needing to be done myself to get the words/characters to show proper in non-English languages? Perhaps the server needs to explicitly specify a "Content-Type" header with value "UTF-8"?
I'm going to answer anyway, I'm guessing you aren't getting your json in UTF-8 as i had a similar problem, I believe json won't come any other way.
Complete Example
The only things to concern yourself with this is setting the encoding for the InputStreamReader and creating the JSONObject
private DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://myjsonurl.com/search?type=json");
// Depending on your web service
httppost.setHeader("Content-type", "application/json");
try
{
String result = null;
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
JSONObject myJObject = new JSONObject(sb.toString();
}
catch (Exception e)
{
}
finally
{
try{if(inputStream != null)inputStream.close();}catch(Exception none){}
}
add this line when you connect to mysql:
mysql_set_charset('utf8', $con);
ex:
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_set_charset('utf8', $con);
mysql_select_db(DB_DATABASE);

Categories

Resources