I created an android application and I'm using Google Translate Rest service.
I used this URL to send a request in order to translate a source text.
"https://www.googleapis.com/language/translate/v2?key=" + apiKey + "&target=en&q=" + text"
As you can see the source language was not set in order to enable the service to detect
the language of the given text.
When I put something in Hebrew the result I get is question mark.
For example if I enter "שלום עולם" which need to be translated into "hello world" in English,
I get the result "???? ????".
I tried with other languages like Russian or Spanish. It worked fine with Spanish, but
with the Russian language it worked like Hebrew.
Is there any bug with the API or am I doing something wrong?
Update:
encoded = URLEncoder.encode(textToTranslate,"UTF-8");
url = new URL("https://www.googleapis.com/language/translate/v2?key=" + apiKey + "&target=en&q=" + encoded);
Thanks,
Elior
You need to encode the text before pass as q parameter.
For example for the string שלום עולם:
String original = "שלום עולם";
String encoded = null;
try {
encoded = URLEncoder.encode(original, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
The value of the encoded variable will be %D7%A9%D7%9C%D7%95%D7%9D+%D7%A2%D7%95%D7%9C%D7%9D and the URL became:
"https://www.googleapis.com/language/translate/v2?key=" + apiKey + "&target=en&q=%D7%A9%D7%9C%D7%95%D7%9D+%D7%A2%D7%95%D7%9C%D7%9D"
Related
I have a base 64 encoded key file. If I open it by Text Editor, I see 4 lines like this:
Then I copy the text and paste to Android Studio, I see the symbol "\n" is generated as below:
This pubic key doesn't work. So I tried :
Remove all "\n" symbol. Still doesn't work.
Replace the "\n" symbol with the space " ". Again doesn't work.
Could you please show me where I am wrong?
Rather than pasting the contents of the file into a string, why not just copy the file itself into your assets folder. For example:
public String readPublicKeyFromFile() {
String publicKeyString; = "";
try {
InputStream is = getAssets().open("public_key.txt");
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
// Convert the buffer into a string.
return new String(buffer);
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
Its android studio console character limitation that it shows long string in multiple lines.
Best way is to copy that string in any text editor(notepad) and make it single line string and then paste it to studio.
Another way is just delete that '\n' character from your string it will be single line string.
e.g.
private static final String = "abcdefgh" +
"ijklmnop" +
"qrstuvwxyz";
just remove '\n' character from your string.
If you creating the "publickey.txt" (base64) file, just use "Base64.NO_WRAP" flag for creating the file. This flag not allow the "\n" character.
By default it takes the "Base64.DEFAULT" flag, so every 64 characters after "\n" will be added automatically.
// for encoding the String with out \n
String base64Str=Base64.encode(your_string,Base64.NO_WRAP);
// for decoding
byte[] resByte=Base64.decode(base64Str,Base64.NO_WRAP);
// convert into String
String resStr=new String(resByte,"UTF-8");
I need to post data to Webview.
I found from some of the links the below code:
WebView webview = new WebView(this);
setContentView(webview);
String url = "http://www.example.com";
String postData = username=my_username&password=my_password";
webview.postUrl(url",EncodingUtils.getBytes(postData, "BASE64"));
But in my android studio I see EncodingUtils as deprecated
Can anyone help me what is the alternative for EncodingUtils to post data to Android WebView?
Try like below...
Java:
WebView webview = new WebView(this);
setContentView(webview);
String url = "http://www.example.com";
String postData = "username=" + URLEncoder.encode(my_username, "UTF-8") + "&password=" + URLEncoder.encode(my_password, "UTF-8");
webview.postUrl(url,postData.getBytes());
Kotlin:
val webview = WebView(this)
setContentView(webview)
val url = "http://www.example.com"
val postData = "username=${URLEncoder.encode(my_username, "UTF-8")}" +
"&password=${URLEncoder.encode(my_password, "UTF-8")}"
webview.postUrl(url, postData.toByteArray())
This is a simple workaround.
String html = "<!DOCTYPE html>" +
"<html>" +
"<body onload='document.frm1.submit()'>" +
"<form action='http://www.yoursite.com/postreceiver' method='post' name='frm1'>" +
" <input type='hidden' name='foo' value='12345'><br>" +
" <input type='hidden' name='bar' value='23456'><br>" +
"</form>" +
"</body>" +
"</html>";
webview.loadData(html, "text/html", "UTF-8");
I know this is not the best method but this works.
I would like to add a few things to the answer as I had to work on same and found some info could help complete the answer to this question.
First thing is the need for such a scenario. My need was that I am
creating a payment gateway client for native applications in android.
Second thing is that the URL you are opening needs to perform some
operations right. Hence you must enable your webView to enable
such operations or else things might not work. For example if your
URL is executing some java script, than you must enable java script
for your webview. This can be done as shown below :
val set = webview.settings
set.javaScriptEnabled = true
Normally this will enable trivial things such as timers, returning results etc on your webview.
Third thing is a case when your webView needs to call methods of your android app. This can be done by adding some JavaScript Interface as shown below :
webview.addJavascriptInterface(WebAppInterface(), "Android")
Where WebAppInterface() is a simple class which atleast one method annotated with #JavascriptInterface as shown below :
class WebAppInterface() {
#JavascriptInterface
fun showToast(status: String) {
//show toast here or handle status
}
}
The name Android will be the one which will be injected into your URL as a variable and you can call the methods of your android WebAppInterace from that URL as shown below:
Android.showToast("From WebPage")
Last thing is your postURL method which is somewhat like :
webview.postUrl(actionUrl, params.toByteArray(Charsets.UTF_8))
This method has couple of things that it takes as default. First is that request type is taken as default POST as the name suggest.
Header content-type can be default taken as application/x-www-form-urlencoded and
most important params it takes as & separated key value pairs as shown :
val params = "MERCHANT_ADDR=" + addr + "&CHANNEL=android"
We must pass byteArray of this string which is shown in post URL callback.
Now after your API is hit and it in some cases loads a callback url, from that call back URL using the JavaScript Interface, you can return result to your application and close the webview.
I hope it helps people.
try this:
You need to URL-encode the parameter value before sending it.
String postData = "fileContents=" + URLEncoder.encode(fileCon, "UTF-8");
For those who came here by trying to put a html body as a postData and not working,
try to put your string body as something below:
val htmlCode = "https://ramdom.user.me"
val postData = "{\n" +
"\t\"token\": \"963966f649\"\n" + "}"
webview.postUrl(htmlCode, postData.toByteArray())
I hope to save someone`s life. :-)
I use the source code from this website to create a new PDF file, and it works.
The problem is that when I write Chinese in PDFWriteDemo.java : mPDFWriter.addText(70, 50, 12, "各位好"); , it can't display the characters in the PDF file normally.
Instead, it shows ???.
Try to change this line:
outputToFile("helloworld.pdf",pdfcontent,"ISO-8859-1");
to:
outputToFile("helloworld.pdf",pdfcontent,"UTF-8");
UPDATE
Considering that it might be the encoding issue, you'll need to follow these sequence to change the Font and Encoding:
First we found that in PDFWriterDemo.java, this line defines the Font and encoding:
mPDFWriter.setFont(StandardFonts.SUBTYPE, StandardFonts.COURIER, StandardFonts.WIN_ANSI_ENCODING);
In which the mPDFWriter is a class that defined in PDFWriter.java.
As you can see in PDFWriter.java there's an method:
public void setFont(String subType, String baseFont, String encoding) {
mCurrentPage.setFont(subType, baseFont, encoding);
}
Where mCurrentPage is a class defined in Page.java
Here in Page.java
public void setFont(String subType, String baseFont, String encoding) {
IndirectObject lFont = mDocument.newIndirectObject();
mDocument.includeIndirectObject(lFont);
lFont.setDictionaryContent(" /Type /Font\n /Subtype /" + subType + "\n /BaseFont /" + baseFont + "\n /Encoding /" + encoding + "\n");
mPageFonts.add(lFont);
}
Then you'll find that actually they didn't embed the font into the package, they just provide a font's name and with correct encoding the PDF reader will load them automatically.
Thus the solution of what I think, is to edit the StandardFonts.java to add the PDF standard fonts for rendering Chinese characters and a correct encoding.
I'm trying to download images from a website and my code is working fine in most cases, but I can't download from this URL http://www.liveandlocal.org.uk/images/ShowPics/Steiny’s%20Blues%20-%20Such%20Sweet%20Thunder.jpg
The difference between this and the other URLs is that this one has a dash. I'm fairly certain this is the problem. Is there a way around this?
My error is java.io.filenotfoundexception
My initial code was:
imgLink = "http://www.liveandlocal.org.uk/images/ShowPics/" + Show + ".jpg";
imgLink = imgLink.replace(" ", "%20");
This gave me links like: http://www.liveandlocal.org.uk/images/ShowPics/The%20Atlantics.jpg
which works, but this didn't work for the link I posted at the top.
So now I've tried:
try {
Show = URLEncoder.encode(Show, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
imgLink = "http://www.liveandlocal.org.uk/images/ShowPics/" + Show + ".jpg";
Which doesnt work for any of my links, such as http://www.liveandlocal.org.uk/images/ShowPics/The+Atlantics.jpg
If you copy and paste the link at the start of this post into your browser it will work, so it is just not working on Android.
imgLink = "http://www.liveandlocal.org.uk/images/ShowPics/Steiny%E2%80%99s%20Blues%20-%20Such%20Sweet%20Thunder.jpg"
working fine for me, tested it, replace the characters thus accordingly and '.
- is fine.
Your url contains letters which are not suited for urls (' in this case).
You can encode your url as the following:
String encodedUrl = URLEncoder.encode(normalUrl, "UTF-8");
URLEncoder
I have some different language html file for different language environment, and all of those html files contain images. Now I want to show suitable html files with WebView adapt to current language of Android. How can I do that? Thanks.
You can give special names for non-English files like file-de.html for German and then use the following code:
private static String getFileName() {
Configuration config = getResources().getConfiguration();
InputStream stream = null;
try {
String name = "file-" + config.locale.getLanguage() + ".html";
stream = getAssets().open(name);
return name;
} catch (IOException exception) {
return "file.html";
} finally {
if (stream != null) {
stream.close();
}
}
}
You might use "string values" to get Android language dependent HTML file names without using any additional java code and just using getString(). Here's an example for 2 languages:
In file values/strings.xml:
<string name="html_help_basepage">en_help.html</string>
In file de/strings.xml:
<string name="html_help_basepage">some_german_help.html</string>
And so on...
For your Java code (loading from local file in asset folder as in question)
helpView = (WebView) findViewById(R.id.wv_help);
String adaptedToLanguage = getString(R.string.html_help_basepage)
helpView.loadUrl("file:///android_asset/" + adaptedToLanguage);
No additional Java code is needed. I hope this is helpful and answers the question.
Added a new answer, which should be more precise by providing an example.