How to encode a StringBody? - android

I have a problem when I want to create a StringBody which contains a "ñ" or any extended character. I need to encode it to UTF-8 and I have tried to define the Charset (UTF-8) like this:
new StringBody(i.getValue(), Charset.forName(HTTP.UTF_8));
It doesn't work. Are there any way to encode this String body to UTF-8?

Below is a snippet working with string data type. Try to change the String to StringBody. Hope it works.
String name = "John";
String encodedName = URLEncoder.encode(name, "UTF-8");

Related

How to Pass JsonString As a Parameter in Android WebAPI

string sortbyObj ="{'SortName':'DueDate','SortType':'asc'}";
string FiltersObj = "{'StartTime':'1/8/2016','EndTime':'3/8/2018','Ovedue':false,'Status':-1,'Priority':-1,'AssignedTo':-9999,'FollowUpBy':-9999,'Mytasks':false,'StartsWith':'','Endswith':''}";
string apiUrl = MainActivity.GetData("http://" + MainActivity.IPAddress + "/JTASKTest/api/jtasks/GetItemList?uName=admin&tgId=1&sortbyObj='"+sortbyObj.ToString()+"'&FiltersObj='"+FiltersObj.ToString()+"'");
I am trying to send string as a Parameter But it is giving 'Input string Formate not correct' Exception . Please Help Me how can i send this two Strings as a parametrs Through WebApi
If your API recognizes the url encoded Json String then I would suggest you to use something like this
string url = "http://yourapi/chat?msg=" + HttpUtility.UrlEncode(msg);
Detail answer here
in your case:
string apiUrl = MainActivity.GetData("http://" + MainActivity.IPAddress +"/JTASKTest/api/jtasks/GetItemList?uName=admin&tgId=1&sortbyObj='"+ HttpUtility.UrlEncode(sortbyObj.ToString())+"'&FiltersObj='"+HttpUtility.UrlEncode(FiltersObj.ToString()));
but in this case you should have to make sure that your API understands the URL Encoded JSON

convert byteArray to string to initialize jsonObject

i have byteArray.
is it possible to convert byteArray to String?
please check my code
byte[] data = **some_byte_array**
JSONObject jsonObject = new JSONObject(data);
how do i fix this.
Try this
String decoded = new String(bytes, "UTF-8");
There are a bunch of encodings you can use, look at the Charset class in the Sun javadocs.
The "proper conversion" between byte[] and String is to explicitly state the encoding you want to use. If you start with a byte[] and it does not in fact contain text data, there is no "proper conversion". Strings are for text, byte[] is for binary data, and the only really sensible thing to do is to avoid converting between them unless you absolutely have to.
answer credit goes to https://stackoverflow.com/a/1536365/4211264
Yes you can convert byte array to String using one of the String constructors like this :
String myString = new String(yourByteArray);
Documentation for the same:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#String(byte[])
All the best :)

How Can I change a string to the UTF-8 format in android

How Can I change a string to the UTF-8 format in android? For example when I get a text string from server I want change the text format to the UTF-8. How can I do this?
String getText = text; // this text variable has a value from the server and now I want change it to UTF-8 format.
String objects hold UTF-16 data internally. If what you want is to encode a String as UTF-8 for exporting, you need to convert it to a UTF-8 encoded byte[] array, such as with the String.getBytes(Charset charset) or String.getBytes(String charsetName) method, eg:
byte[] byteArray = text.getBytes(StandardCharsets.UTF_8);
byte[] byteArray = text.getBytes("UTF-8");
Hi You could use the String constructor with the charset parameter:
try
{
final String s = new String("AnyStringThatYouwant to convert", "UTF-8");
}
catch (UnsupportedEncodingException e)
{
Log.e("utf8", "conversion", e);
}

How would you format this URL, it is giving me "Illegal character in path at index 70"?

I'm getting "Illegal character in path at index 70". And the final URL on debugging is coming like:
http://dev.example.com/Service/MyService.svc/CheckEmail/{0}
But I want the URL to be like:
http://dev.example.com/Service/MyService.svc/CheckEmail/rashid
I'm little new in Android, how can I achieve my desired result? Any help with explanation will be appreciated.
Below is the code:
String baseUrl = "http://dev.example.com/Service/MyService.svc/";
String url = String.format("CheckEmail/{0}", name);
HttpGet httpGet = new HttpGet(baseUrl + url);
Java doesn't use {} syntax for String.format. You confused it with a C# language. Java uses printf-like %-syntax for arguments.
Se here for details. In your case you should use
String url = String.format("CheckEmail/%s", name);
Just try this way may help you
String url = String.format("CheckEmail/%s", name);

how to url encode in android?

I am using grid view for displaying image using xml parsing,i got some exception like
java.lang.IllegalArgumentException: Illegal character in path at
index 80:
http://www.theblacksheeponline.com/party_img/thumbspps/912big_361999096_Flicking
Off Douchebag.jpg
How to solve this problem? I want to display all kind of url,anybody knows please give sample code for me.
Thanks All
URL encoding is done in the same way on android as in Java SE;
try {
String url = "http://www.example.com/?id=123&art=abc";
String encodedurl = URLEncoder.encode(url,"UTF-8");
Log.d("TEST", encodedurl);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Also you can use this
private static final String ALLOWED_URI_CHARS = "##&=*+-_.,:!?()/~'%";
String urlEncoded = Uri.encode(path, ALLOWED_URI_CHARS);
it's the most simple method
As Ben says in his comment, you should not use URLEncoder.encode to full URLs because you will change the semantics of the URL per the following example from the W3C:
The URIs
http://www.w3.org/albert/bertram/marie-claude
and
http://www.w3.org/albert/bertram%2Fmarie-claude
are NOT identical, as in the second
case the encoded slash does not have
hierarchical significance.
Instead, you should encode component parts of a URL independently per the following from RFC 3986 Section 2.4
Under normal circumstances, the only
time when octets within a URI are
percent-encoded is during the process
of producing the URI from its
component parts. This is when an
implementation determines which of the
reserved characters are to be used as
subcomponent delimiters and which can
be safely used as data. Once
produced, a URI is always in its
percent-encoded form.
So, in short, for your case you should encode/escape your filename and then assemble the URL.
You don't encode the entire URL, only parts of it that come from "unreliable sources" like.
String query = URLEncoder.encode("Hare Krishna ", "utf-8");
String url = "http://stackoverflow.com/search?q=" + query;
URLEncoder should be used only to encode queries, use java.net.URI class instead:
URI uri = new URI(
"http",
"www.theblacksheeponline.com",
"/party_img/thumbspps/912big_361999096_Flicking Off Douchebag.jpg",
null);
String request = uri.toASCIIString();
you can use below method
public String parseURL(String url, Map<String, String> params)
{
Builder builder = Uri.parse(url).buildUpon();
for (String key : params.keySet())
{
builder.appendQueryParameter(key, params.get(key));
}
return builder.build().toString();
}
I tried with URLEncoder that added (+) sign in replace of (" "), but it was not working and getting 404 url not found error.
Then i googled for get better answer and found this and its working awesome.
String urlStr = "http://www.example.com/test/file name.mp4";
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();
This way of encoding url its very useful because using of URL we can separate url into different part. So, there is no need to perform any string operation.
Then second URI class, this approach takes advantage of the URI class feature of properly escaping components when you construct a URI via components rather than from a single string.
I recently wrote a quick URI encoder for this purpose. It even handles unicode characters.
http://www.dmurph.com/2011/01/java-uri-encoder/

Categories

Resources