How do I parse a HTTP Response of following format - android

I am using the bulk sms api to trigger send an sms to mobile number in and android phone. The format of the bulk sms api is follows
http://xxx.xxx.xxx/bulksms/bulksms?username=fds-xxx&password=xxx&type=0&dlr=1&destination=9422522891,8275004333&source=xxx&message=18%20December
The following is the response I can get in android as string using code
bytesSent = httpclient.execute(httppost, res);
response below
1701|919422522891:224c1214-bb95-414d-ba76-77db95370545,1701|918275004333:5e93a439-2644-4455-9f01-f27e6cf0cde6
How do I parse this response like key value pairs ?
A little success with following code , but it fails when the regex char is '|'
public String[] split(String regex,String input)
{
input = "1701|919422522891:224c1214-bb95-414d-ba76-77db95370545,1701|918275004333:5e93a439-2644-4455-9f01-f27e6cf0cde6";
regex = "|"; // does not work
//regex = ":"; // works correct
String[] soso = Pattern.compile(regex).split(input, input.length());
for (String s : soso) {
Log.e("TAG",s.toString());
}
return null;
}
for regex char '|'
I get a Log output as single characters string array like {"1","7","0",........}
UPDATE
regex = "\\|" // works fine

Use the split() method of String to split the response into different entries.
Loop through the resulting array
use split() again to separate keys from values
store the result in a map, result[0] is the key,result[1] is the value
if you need to maintain order make sure you use a map that does that, e.g. LinkedHashMap

Related

Flutter parse unicode characters not working

I have the following string coming from my backend server \u25CF\u25CF\u25CF and when I decode it with UTF-8 it's working fine in the iOS native app, But when I try to parse it in flutter I'm not able to get the converted value. I have tried the following approaches but none worked
String converted = Utf8Decoder().convert(userName.codeUnits);
String uname = utf8.decode(userName.runes.toList());
String runes = String.fromCharCodes(Runes('$userName'));
Does anyone know how we can fix this? The real value should be 3 dots after conversion.
Update
This is json parsing code
if (response.statusCode == 200) {
Map<String, dynamic> postResponse = response.data;
var postsJson = postResponse["posts"];
for (var postObjet in postsJson) {
Map<String, dynamic> finalMap = Map<String, dynamic>.from(postObjet);
Post p = Post.fromMap(finalMap);
posts.add(p);
}
}
Sample JSON Response
The Chat service we\u2019ve been paying for since our launch
You are starting with a string with unicode escapes and you want to end up with a string containing the actual unicode characters. This is easy if the input contains only unicode escapes as you can simply strip out the \u and parse the hex to a code point.
final input = '\\u25CF\\u25CF\\u25CF'; // note I have to double the \ as this is source code
var hexPoints = input.split('\\u').sublist(1);
print(hexPoints); // [25CF, 25CF, 25CF]
// convert to a string from codepoints, parsing each hex string to an int
final result = String.fromCharCodes(
hexPoints.map<int>((e) => int.parse(e, radix: 16)).toList(),
);
print(result); // dot, dot, dot
The more general solution where there may be a mixture of escaped and unescaped characters is to use a regular expression that matches \xnnnn, parses the nnnn as hex and replaces it with that code point.
String sanitize(String s) => s.replaceAllMapped(
RegExp(r'\\u([0-9a-fA-F]{4})'),
(Match m) => String.fromCharCode(int.parse(m.group(1)!, radix: 16)),
);
Use it like this:
print(sanitize('ab\\u25CF\\u25CF\\u25CFcd')); //ab<dot><dot><dot>cd
Finally, note that if these escaped strings are appearing inside JSON, the JSON decoder will automatically convert them.
Consider using the characters package instead of runes. Seems like it can solve your problem.

Retrofit GET request with arrays in Query params

How to send GET request with query params like this?
key1=["S","I","D"]&key2=[["A","X",0],["X","Y","Z"]]
According to retrofit java documents, you can do like below.
Values are converted to strings using Retrofit.stringConverter(Type, Annotation[]) (or Object.toString(), if no matching string converter is installed) and then URL encoded. null values are ignored. Passing a List or array will result in a query parameter for each non-null item.
Array/Varargs Example:
#GET("/friends")
Call<ResponseBody> friends(#Query("group") String... groups);
Calling with foo.friends("coworker", "bowling") yields /friends??> group=coworker&group=bowling.
So you can do something like this
#GET("/something")
Call<ResponseBody> getSomething(#Query("key1") String[] key1,
Query("key2") String[] key2 );
foo.getSomething(key1, key2)
Update - above is the standard way to query parameters with multiple values
In order to send array as string, you can do like below
Parameter names and values are URL encoded by default. Specify encoded=true to change this behavior.
#GET("/something")
Call<ResponseBody> getSomething(#Query(value="key1", encoded=true) String key1);
Calling with foo.getSomething("['S','I','D']")) yields /something?key1=['S','I','D'].
Since retrofit doesn't recognize your custom array type, you have to consider parameters type String, then build your parameter like "["S","I","D"]" before pass to retrofit method.
For example create your parameter:
String parameter = "["
int arraySize = array.size()
for(int i = 0; i < arraySize; i++) {
parameter += "\"" + array.get(i) + "\"";
if(i != arraySize - 1) {//Append ',' except last element
parameter += ",";
}
}
parameter += "]";
Output for array with 'S','I' and 'D' elements is ["S","I","D"] String.
Now you can pass it as retrofit parameter.

How do I read only a specific part of the string in Android Studio?

If a send a string in the following format: 1234,1234,1234,1234; from Arduino to Android Studio (java (intelliJ)) based. with the amount of characters between every komma changing. How do i make it so that my code only reads the string from for example 0 to the , Or from the first , to the second ,?
If you are using Java, I would recommend looking into the Java.String.split() method. This method will split your string in an array of strings, depending on your delimiter. For example :
String s = "1234,1234,1234,1234";
String[] result = s.split(",");
You can split the input string based on any special character,in your case ,, as follows
String inputString = "1234,1234,1234,1234";
String[] separated = inputString.split(",");
Log.i("MainActivity",separated[0]) // prints the first string which is 1234
// to loop over all strings
for(String s : separated){
Log.i("MainActivity",s)
}

How to get this data in json fromat?

I got this data in PayUMoney and to show the user But problem how to get this data in json or key value pair format any one know that please help!!
addedon=2019-11-21+17%3A06%3A42&productinfo=FINE&firstname=Creataum+Test+User&
Assuming that u have got it as String following code will print the key value pair from the string
String x ="addedon=2019-11-21+17%3A06%3A42&productinfo=FINE&firstname=Creataum+Test+User&";
String pair[] = x.split("&");
Log.e("pairs", Arrays.asList(pair).toString());
for (int i=0;i<pair.length;i++){
String key[] = pair[i].split("=");
Log.e("pair:","key= "+ key[0]+" value= "+key[1]);
}
It seems the string is both URL encoded (the %3A) and JSON encoded (the &).
You have to decode the string and then split by '&' and then split each pair to key and value by '='.
You can see here how to JSON decode: Decoding JSON String in Java
URL decoding can be done with Java's URLDecoder class: https://docs.oracle.com/javase/7/docs/api/java/net/URLDecoder.html
For this example I'll just assume the only encoded characters are %3A and &.
String payumoney = "addedon=2019-11-21+17%3A06%3A42&productinfo=FINE&firstname=Creataum+Test+User&";
// String decoding.
payumoney = payumoney.replaceAll("%3A", "-");
payumoney = payumoney.replaceAll("&", "&");
HashMap<String, String> params = new HashMap<String, String>();
String[] pairs = payumoney.split("&");
for (String pair : pairs) {
String[] keyValue = pair.split("=");
params.put(keyValue[0], keyValue[1]);
}
This looks like a String with mixture of URL encoding (like %3A for :) and HTML characters (like & for &).
I believe you can try decoding it and then split data like say by & to get data for each key and then further split by = to get value for that key.
For URL decoding you can try like
String decoded = java.net.URLDecoder.decode(url, "UTF-8");
You can simply use String replaceAll() function to create the json.
str= str.replaceAll("=", "\"");
str= str.replaceAll("&", "\",\"");
str= "{\""+ str+ "\"}";

I want to know how to send 5 strings in Android to Arduino to store in variable?

I've used Amarino receive 5 String on Android from 5 edittexts then send to Arduino.
//Code to send a String. One of five Strings.
Amarino.sendDataToArduino(MainActivity.this,"HC-05",'a',name);
In Arduino I've created functions for each String for save in variables. But I can't pass compiling. There is an error messages "void value not ignored as it ought to be" .
//Arduino code. I take part of custom function code that relate Meetandroid.
void getUsername(byte flag, byte numOfValues)
{
// first we need to know how long the string was in order to prepare an array
// big enough to hold it.
// you should know that: (length == 'length of string sent from Android' + 1)
// due to the '\0' null char added in Arduino
int length = meetAndroid.stringLength();
// define an array with the appropriate size which will store the string
char data[length];
// tell MeetAndroid to put the string into your prepared array
//Can't compile Here
username = meetAndroid.getString(data);
}
I've also tried to send array of String. There is a function in Amarino but I can't find the receive function. I dont know what I may miss. How to solve this problem?
//data is array of String in Andriod
Amarino.sendDataToArduino(MainActivity.this,"HC-05",'a',data);
meetAndroid.getString(data) has no return value. Thus, you can't assign it to username.
char data[length];
username = meetAndroid.getString(data);
Change that to:
char data [] = new char[length];
meetAndroid.getString(data);
String username = data.toString();
return username; // and change function return type to String
You are sure byte data [] = new byte[length]; isn't more appropriate?

Categories

Resources