Base64 encoding for post in WebView - android

I am facing a problem with the encoding of a string. First of all, let me explain the context:
I need to make a post and load the content in a webView. For this requirement I need to use webView.postUrl(String url, byte[] postData).
I saw a lot of examples using this method along with EncodingUtils.getBytes("stringToEncode","base64").
The good news is that this works for me. The bad news is that this class is deprecated and you need to add the next code to the gradle file:
android {
useLibrary 'org.apache.http.legacy'
}
I would like to avoid this and use the way it should be.
As far as I know the replacement for this deprecated class is android.util.Base64.
I tried the next codes without success:
webView.postUrl("url", Base64.encode("paramsToEncode".getBytes(),Base64.DEFAULT));
webView.postUrl("url", Base64.encode("paramsToEncode".getBytes(StandardCharsets.UTF_8),Base64.DEFAULT));
According to the documentation of EncodingUtils:
Converts the specified string to a byte array. If the charset is not
supported the default system charset is used. Parameters: data - the
string to be encoded charset - the desired character encoding Returns:
The resulting byte array.
And the documentation for Base64:
input byte: the data to encode flags int: controls certain features of
the encoded output. Passing DEFAULT results in output that adheres to
RFC 2045. Returns byte[]
So I do not know what I am doing wrong. If you struggled with this kind of problem I would appreciate some comments :).

Not sure why your example doesn't work, but the below code seems to be working for me:
webView.postUrl(url, urlParams.getBytes(Charset.forName("UTF-8")));

Related

Keep special chars when using deep link with query params with Navigation Jetpack

I am sending a raw JSON as a String in URI navigation with Navigation library. It looks like this.
findNavController().navigate(
Uri.parse("android-app://androidx.navigation/checkout/${Gson().toJson(orderSummary)}"),
NavOptions.Builder()
.setEnterAnim(R.anim.transition_slide_in_right)
.setExitAnim(R.anim.transition_slide_out_left)
.setPopExitAnim(R.anim.transition_slide_out_right)
.setPopEnterAnim(R.anim.transition_slide_in_left)
.build()
)
}
and then I retrieve it like so
arguments?.getString(key)
This works as expected expect for one test case - special chars are not decoded when retrieving the json (specifically % sign)
So when checking the value of this Uri.parse("android-app://androidx.navigation/checkout/${Gson().toJson(orderSummary)}"), it looks as expected contains the % sign but when doing arguments?.getString(key) the % sign is replaced with ? for an unknown char.
How to keep the special chars when getting the string from the arguments?
I just fall in same situation, and was thinking about solution for this.
Frankly I don't know if this is the best solution or not, but I've encoded my json string, then when receiving it, I've decode it first then convert it back to original object.
HYG:
Encode deep-link url when sending params like below :
val encoded = URLEncoder.encode(Gson().toJson(orderSummary), StandardCharsets.UTF_8.name())
findNavController().navigate(Uri.parse("android-app://androidx.navigation/checkout/${encoded}}"))
Then when receiving your object in the other fragment, you just need to decode it first
val decoded = URLDecoder.decode(arguments?.getString(key),StandardCharsets.UTF_8.name())
Gson().fromJson(decoded, StandardCharsets.UTF_8.name()),OrderSummary::class.java)
Hope this helping someone facing same issue.
I ran into a similar issue, I was trying to pass a string navigation argument that contained a '%' character. Using URLEncoder and URLDecoder had issues for me because the navigation library itself does some decoding so the argument would come back to me already partially decoded and I would get a crash trying to use URLDecoder.
If you look in NavDeepLink.kt in the navigation library you can see in a couple spots they call Uri.decode on the arguments. So if you encode the strings with Uri.encode before navigating it should work properly.
val encoded = Uri.encode(Gson().toJson(orderSummary))
findNavController().navigate(Uri.parse("android-app://androidx.navigation/checkout/${encoded}}"))
Gson().fromJson(arguments?.getString(key), OrderSummary::class.java)

How to get json data from wiki api?

Does anyone have any idea how to use
wikipedia Api for getting some basic json data base on search keyword like:
the Title , some short content or summary ,page url and the most important thing is the image.
I tried to use wiki api sandbox but i can't understand how to use it and set it like i want.
https://en.wikipedia.org/wiki/Special:ApiSandbox#action=query&list=search&format=json&srsearch=dog&srnamespace=4&srprop=snippet&srlimit=15&generator=allimages
Any idea?
It's very simple, Here is a test example:
https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles=donald%20Trump&format=json
read the docs
https://en.wikipedia.org/w/api.php
https://www.mediawiki.org/wiki/API%3aProperties#revisions_.2F_rv

Picasso won't load Google Static Map

I'm trying to load an static map using this url:
http://maps.googleapis.com/maps/api/staticmap?center=43.137022,13.067162&zoom=16&size=600x400&maptype=roadmap&sensor=true&markers=color:blue|43.137022,13.067162
I'm doing it with Square's Picasso, but it fails to load.
With some tests I've to the conclusion that the char | is the one messing up Picasso. Any idea on how to overcome this issue?
Picasso appears to expect a URL-encoded URL. This means that the values of form variables need to be URL-encoded, the way they would if this were a submitted HTML form.
Alphanumeric characters do not need escaping, which is why most of your URL is fine. However, the markers parameter contains special characters, particularly that |, which need to be converted into URL-encoded values.
If you were programmatically generating the URL by pieces, you might use URLEncoder and encode() to handle this conversion for you.

how to send protobuf as part of XML

i have create a protobuf sample code in android as follows
Person john =
Person.newBuilder()
.setId(1234)
.setName("John Doe")
.setEmail("jdoe#example.com")
.addPhone(
Person.PhoneNumber.newBuilder()
.setNumber("555-4321")
.setType(Person.PhoneType.HOME))
.build();
now i want to send this john object as a part of xml building block over network
so far i have seen following methods so that i can send bytes over network
john.toByteArray() and john.toByteString()
but i think when i will embed into xml tag as follows it will be the string representation only and from that i can not get the data back
"<data>" + john.toByteArray() + "</data>"
so how can i pass the protobuf message with XML ?
note: i don't want to use the base64 encoding as it will eventually increasing the size of a block
The fundamental problem here is that protobuf encoding is binary while XML is text. You can't embed binary data directly into text; you need to encode it as text somehow.
Unfortunately, there is simply no way to do that without increasing the data size. If size is your concern, base64 is likely your best option -- this is exactly what it was designed to do.
Another possibility would be to encode the message in protobuf text format using .toString() and then parse it using com.google.protobuf.TextFormat. This will produce a human-readable encoding, but it will be much larger than the binary encoding.
Yet another option would be to write a custom translator which uses the protobuf reflection iterfaces (e.g. com.google.protobuf.Message#getField()) to read individual fields and convert them to nested XML elements. However, this is complicated and will probably end up taking even more space than protobuf text format.
These are the options that I'm aware of:
using this 3rd party library.
With this method, you can generate xml that you can embed in your outer xml
using the TextFormat API, though parsing seem to be possible only in c.
from protobuf to string format:
TextFormat.shortDebugString((myProtobufMessage);
from string format to protobufm in c++ code
TextFormat:parseFromString(dataString, &myProtobufMessage);
(I didn't try this myself, but I saw this reference).
With this method you generate a String that you can embed in your XML, and on the receiving end, take that String and convert it to protobuf Message objects.
using protobuf > binary > base64 - instead of xml altogether. You can probably send all the data in the wrapping XML inside the protobuf message. This is what I do.
With this method you can forget about XML and use protobuf for everything. This is the original purpose of protobuf, and this is what it is best for.

Get neat content from Wiki page. (MediaWiki API)

I want to get a content page from Wiki in this format (the picture below) then show it in WebView. It means the content includes text and links.
I tried this but the output seems to be messy.
http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles=Albert_Einstein&format=xmlfm
I stumbled across this answer a year later and would like to note that the ?action=render parameter has been depreciated as of this post.
The recommended method is to use the Mediawiki API to parse the wikitext.
You want index.php?action=render; an example. This returns the HTML of the page content with no sidebar/header/footer HTML. You'll have to match and remove infoboxes yourself.
Reference: MediaWiki — Manual:Parameters to index.php.
You can use HTML generated by mediawiki instead of wikicode.
BTW: look at this

Categories

Resources