Android - issue with encoding Arabic words - android

I face problem in encoding Arabic response from web , I am using volley to call web service
my tries to fix this issue.
I created custom request then parse network response with utf-8 encoding when I log to check result it give me strange writing here is my log {"data":null,"msg":"لا يوجد تنبيهات","status":false} and here is my full class , I made some tries as well according to previous answer fixEncodingUnicode but all tries failed .
I appreciate any help thanks
import android.text.Html;
import android.util.Log;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
* Created by mina on 7/28/2016.
*/
public class myJsonObjectRequest extends JsonObjectRequest {
public myJsonObjectRequest(int method, String url, String requestBody, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, requestBody, listener, errorListener);
}
public myJsonObjectRequest(String url, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(url, listener, errorListener);
}
public myJsonObjectRequest(int method, String url, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, listener, errorListener);
}
public myJsonObjectRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}
public myJsonObjectRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(url, jsonRequest, listener, errorListener);
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
response.headers.put("Content-Type",
response.headers.get("content-type"));
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
Log.v("network_response", jsonString + "encoding "+ response.headers.get("content-type"));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
private String DecodemyString(String msg) {
try {
return URLEncoder.encode(msg, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}
public static String fixEncodingUnicode(String response) {
String str = "";
try {
str = new String(response.getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String decodedStr = Html.fromHtml(str).toString();
return decodedStr;
}
}

finally I figure nice solution to all who face encoding issue
First : make sure your android studio encoding utf-8 ,
File -> Settings -> Editor -> File Encodings choose utf-8 in encoding project
reference
Second: here is the trick , we need to discover what encoding did we receive , we can approach that in parseNetworkResponse method by called response.headers.get("content-type").
in my case I got charset:utf-8 that mean encoding in utf-8 but in fact its not , how we discover real encoding type here is site detect encoding https://2cyr.com/decode/ , just past text in site and made site handle Select encoding : auto detect
it will return pasted text with all encoding scroll down to find write encoding (you will see your writing in original language )
get source encoding: , displayed as:
in my case I found source encoding : utf-8
displayed as: windows-1254
this why I create method fix encoding issue
public static String fixEncodingUnicode(String response) {
String str = "";
try {
// displayed as desired encoding
^ ^
| |
str = new String(response.getBytes("windows-1254"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String decodedStr = Html.fromHtml(str).toString();
return decodedStr;
}

Related

how to set parameters to volley request (GET request )?

I have a volley request with type GET , I want to pass it the number of page and numbers of posts in each page but it doesnt react to my parameter , here is my request :
(By the way , when I use getParams and getHeaders functions , it wont to anything too)
CustomRequest2 recListReq = new CustomRequest2(Constants.Posts +"?page="+count+"&per_page=1&categories=52" , new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Gson gson = new Gson();
...
and it is my CustomRequest :
public class CustomRequest2 extends JsonRequest<JSONArray> {
/**
* Creates a new request.
* #param url URL to fetch the JSON from
* #param listener Listener to receive the JSON response
* #param errorListener Error listener, or null to ignore errors.
*/
public CustomRequest2(String url, Listener<JSONArray> listener, ErrorListener errorListener) {
super(Request.Method.GET, url, null, listener, errorListener);
}
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONArray(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}

JSONException trying to extend JsonObjectRequest

I am running into a syntax problem but I can't figure out what is wrong. It seems like this thread has the answer but it does work for me.
JSONException: Value of type java.lang.String cannot be converted to JSONObject
I am using Volley I need to extend the JsonObjectRequest so that I can access the http headers in the response. Here is my "CustomRequest"
public class CustomRequest extends JsonObjectRequest {
public CustomRequest(int method, String url, String jsonRequest,
Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
// Save http headers
mHeaders = response.headers;
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
private Map<String, String> mHeaders = new HashMap<>();
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return mHeaders;
}
}
and here my test class:
private void testVolleyRequest() {
String url = "http://my-json-feed";
CustomRequest jsonRequest = new CustomRequest
(Request.Method.GET, url, (String)null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("[TEST]", "Response: " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("[TEST]", "error = "+error.toString());
}
});
Volley.newRequestQueue(this).add(jsonRequest);
}
If I try the sample above I keep getting:
com.android.volley.ParseError: org.json.JSONException: Value <html><head><meta of type java.lang.String cannot be converted to JSONObject
but I am returning a JSONObject:
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
if anyone can spot the issue I greatly appreciate.
thx!
thx boukharist,
the url above was not providing a valid json file. I changed to:
String url = "http://httpbin.org/get?site=code&network=tutsplus";
and it works!

Using custom Volley POST doesn't return anything

I'm trying to use a custom Class that extend the JsonRequest class to send a JSONArrayRequest using POST and a parameter.
public class MethodJsonArrayRequest extends JsonRequest<JSONArray> {
public MethodJsonArrayRequest(int method, String url, JSONObject params, com.android.volley.Response.Listener<org.json.JSONArray> listener, ErrorListener errorListener) {
super(method, url, params.toString(), listener, errorListener);
Log.d("method", Integer.toString(method));
Log.d("jsonRequest", params.toString());
}
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONArray(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
My logs return this:
D/method﹕ 1
D/jsonRequest﹕ {"idShow":"219"}
I'm passing this info to my custom class with this snippit:
...
JSONObject params = new JSONObject();
try {
params.put("idShow", idShow);
}
catch (JSONException e) {Log.d("JSON e", e.getMessage()); }
MethodJsonArrayRequest episodeRequest = new MethodJsonArrayRequest(Request.Method.POST, episodeURL, params, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray myResponse) {
try {
Log.d("myResponse", myResponse.toString());
...
Log of myResponse:
D/myResponse﹕ []
But for whatever reason it does not return anything, I feel like I might not be passing the right thing in for the paramas but I'm not sure, any help is greatly appreciated! Let me know if there is something I didn't include here that might be helpful.
user98239820 answer here was extreamly useful. Instead of extending JsonRequest<JSONArray> class he extended the Request class. I also had to change his new JSONObject to new JSONArray to fit my needs, but by pointing to that class works perfectly.

Post a JSONArray with volley and retrieve a String

I am pretty new to android developing and working with volley and got a few questions. I am trying to send a JSONArray via Post with volley and try to get back a String as response.
I have downloaded the volley files via github and got within the toolbox the JsonArrayRequest.java. This file contains a lot of information which I need for my task so I decided to mix it with the StringRequest.java and got out following:
New class called SendingJsonArray.java
package com.android.volley.toolbox;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.UnsupportedEncodingException;
/**
* A request for retrieving a {#link JSONArray} response body at a given URL.
*/
public class SendingJsonArray extends JsonRequest<JSONArray> {
/**
* Creates a new request.
* #param url URL to fetch the JSON from
* #param listener Listener to receive the JSON response
* #param errorListener Error listener, or null to ignore errors.
*/
public SendingJsonArray(String url, JSONArray JsonArry, Listener<JSONArray> listener, ErrorListener errorListener) {
super(Method.POST, url, JsonArry, listener, errorListener);
}
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONArray(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
The first strange thing is that SendingJsonArray() doesn't contain a int method? It compiles and seems to work without it.
Than I changed the Method.GET to Method.POST. It compiles and seems to work again.
Than I added the "JSONArray JsonArry" within the SendingJsonArray and get following error:
error: no suitable constructor found for JsonRequest(int,String,JSONArray,Listener<JSONArray>,ErrorListener)
[javac] super(Method.POST, url, JsonArry, listener, errorListener);
[javac] ^
[javac] constructor JsonRequest.JsonRequest(int,String,String,Listener<JSONArray>,ErrorListener) is not applicable
[javac] (actual argument JSONArray cannot be converted to String by method invocation conversion)
[javac] constructor JsonRequest.JsonRequest(String,String,Listener<JSONArray>,ErrorListener) is not applicable
[javac] (actual and formal argument lists differ in length)
[javac] 1 error
OK I know what the problem is but I don t know how to solve this. Where is the original constructor and how can I modify mine that this will work?
If I get this working there will be the response listener left. I would try to copy the listener of StringRequest.java and hope that this will work?
#Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
Why are there two and what exactly are they created for? Sorry but the documentation about that isn't really helpful for me :/
Thanks for your help! :)
In order to send a JSONArray as param with volley library I implemented this class called JSONPostArrayRequest, which extends JSONRequest, maybe it can help you:
public class JsonPostArrayRequest extends JsonRequest<JSONObject> {
JSONArray params;
public JsonPostArrayRequest(String url, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener,JSONArray params) {
super(Method.POST, url, null, listener, errorListener);
this.params=params;
}
#Override
public byte[] getBody() {
if ( this.params != null && this.params.length() > 0) {
return encodeParameters( this.params, getParamsEncoding());
}
return null;
}
private byte[] encodeParameters(JSONArray params, String paramsEncoding) {
try {
return params.toString().getBytes(paramsEncoding);
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
}
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}

Google Volley ignores POST-Parameter

I'm currently trying to send a simple POST-request via Google Volley to my server.
Therefore I've written the following lines of code:
Map<String, String> params = new HashMap<String, String>();
params.put("regId", "skdjasjdaljdlksajskl");
JSONObject object = new JSONObject(params);
JsonObjectRequest request = new JsonObjectRequest(Method.POST,
"address_of_my_server/method", object,
successListener, errorListener);
queue.add(request);
But I get an Error 500 returned, which says, that there is a missing parameter (regId). I've tried the same with a GET-Request, but I got the same result.
Only when I'm using a StringRequest with a formatted URL like "address_of_my_server/method?regId=sadlasjdlasdklsj" the server replies with 200.
I get the exact same result when I use a StringRequest like:
StringRequest request = new StringRequest(Method.POST,
"myurl", successListener,
errorListener){
#Override
protected Map<String, String> getParams()
throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("regId", "skdjasjdaljdlksajskl");
return params;
}
};
Why is Volley ignoring my parameters?
I had same issue last week, but it is fixed now.
Your server accepts the Content-Type as form-data, when sending volley's JsonObjectRequest the request's content-type will be application/json so whole params will be sent as one json body, not as key value pairs as in Stringrequest.
Change the server code to get request params from http request body instead of getting it from keys(like $_REQUEST['name'] in php).
Use this helper class:
import java.io.UnsupportedEncodingException;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
public class CustomRequest extends Request<JSONObject> {
private Listener<JSONObject> listener;
private Map<String, String> params;
public CustomRequest(String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
public CustomRequest(int method, String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return params;
};
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
}
Woking example with the issue that Rajesh Batth mentioned
Java code:
JSONObject obj = new JSONObject();
try {
obj.put("id", "1");
obj.put("name", "myname");
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest(
Request.Method.POST, url, obj, listener, errorlistener);
RequestQueue queue = Volley.newRequestQueue(context);
queue.add(jsObjRequest);
PHP-Code:
$body = file_get_contents('php://input');
$postvars = json_decode($body, true);
$id = $postvars["id"];
$name = $postvars["name"];
Note:
The PHP-Vars $_POST and $_REQUEST and $_GET are empty if you are not sending additional GET-VARS.
EDIT:
I deleted my previous answer since it wasn't accurate.
I'll go over what I know today:
Apparently, getParams should work. But it doesn't always.
I have debugged it myself, and it seems that it is being called when performing a PUT or POST request, and the params provided in that method are in a regular GET parameters string (?param1=value1&param2=value2...) and encoded and put in the body.
I don't know why but for some reason this doesn't work for some servers.
The best alternate way I know to send parameters, is to put your parameters in a JSONObject and encode its contents in the request's body, using the request constructor.
Thi's my solution
Solution 1
public void getData() {
final RequestQueue queue = Volley.newRequestQueue(this);
StringRequest postRequest = new StringRequest(Request.Method.POST, "192.168.0.0/XYZ",new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray myArray = new JSONArray(response);
for(int i = 0; i < myArray.length(); i++)
{
JSONObject jObj = myArray.getJSONObject(i);
String category = jObj.getString("nameUser");
Log.e("value", category);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error: ", e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(context,"Error : ").show();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id_user", "1");
return params;
}
};
queue.add(postRequest);
}
Solution 2
remember that if you use php,the $_POST[''];
not working, her more information.
Good Luck

Categories

Resources