JsonSyntaxException when using mobile data - android

I'm using ASP Web API web service which is hosted on SmarterAsp.net to get data in Json format to use them in my android application, when I use Wifi everything works fine and the Json is received correctly but when I use mobile data I get com.google.gson.JsonSyntaxException while parsing the Json received, I checked the received Json string with the debugger and it was malformed and here is what i received :
��������������RMo�#�+՞)��Sڦ9TjeU�)�aX�x\��Ah"�{b�����̾y3OL�G�Y�İ�u²"���r'��J V�#�����(���
���(N9*4MĜ���Fר��m+
���:�7[�/$3��z����c�%q*Ha�OA|�x~������G�8���"?,�4���(��y���N��j�L%���?B
�?S8�lp���(G�rgH�����P�b9����+5��<�n����w_i�G-,��_؋��uz�K;��|�i������� ��|6s����V[J�<�%3���X�������
And here is the method I'm using in android to send and receive data from the ASP Web API web service :
public String PostObject(String url, Object obj) throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
StringEntity stringEntity = new StringEntity(new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create().toJson(obj));
httpPost.setEntity(stringEntity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Accept-Encoding", "gzip");
HttpResponse httpResponse = client.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String rep = EntityUtils.toString(httpEntity);
return rep;
}

It is not malformed. You are accepting gzip compressed data by declaring ("Accept-Encoding", "gzip") in the header.
You can either remove the compression or decompress the data and then use it.
On how to decompress

Related

Problems to send data with spanish chars from android app but not from postman to a restful web service

I have a web service RESTful that it saves to a data base. I pass data with JSON.
If i pass a JSON from POSTMAN, all is ok. If i pass the data (JSON) from an android app, the server can not save to the data base IF THERE ARE SPANISH chars like "ó, ñ, etc.".
Why from postman yes and from android app not?.
I try adding ISO-8859-1 but it doesn't work. Where is the error? Sql server?, android app?, IIS?. If the data doesn't contain spanish chars, all is fine, with spanish chars, it doesn't work.
The code in the android app is like:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost;
httpPost = new HttpPost("http://"...
httpPost.setHeader("content-type", "application/json" );
httpPost.setHeader("charset", "ISO-8859-1");
JSONObject jSONObject = new JSONObject();
try
{
jSONObject.put("Mensaje", params[0].mensaje);
jSONObject.put("IdUsuarioOrigen", params[0].idUsuarioOrigen);
jSONObject.put("IdUsuarioDestino", params[0].idUsuarioDestino);
StringEntity stringEntity = new StringEntity(jSONObject.toString());
stringEntity.setContentType("application/json");
stringEntity.setContentEncoding("ISO-8859-1");
httpPost.setEntity(stringEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
strHttpResponse = EntityUtils.toString(httpResponse.getEntity());
EDIT::::::::::::::::::::::::::::::::::::
I'm debugging for some days. The point is this:
The code in android app is:
...
httpPost.setHeader("content-type", "application/json" );
httpPost.setHeader("charset", "ISO-8859-9");
JSONObject jSONObject = new JSONObject();
try
{
jSONObject.put("Mensaje", params[0].mensaje);
jSONObject.put("IdUsuarioOrigen", params[0].idUsuarioOrigen);
jSONObject.put("IdUsuarioDestino",
params[0].idUsuarioDestino);
StringEntity stringEntity = new
StringEntity(jSONObject.toString());
stringEntity.setContentType("application/json");
stringEntity.setContentEncoding("ISO-8859-9");
httpPost.setEntity(stringEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
strHttpResponse =
EntityUtils.toString(httpResponse.getEntity());
And if i debug httpPost before "httpClient.execute(httpPost);" the httpPost is ok, has the data inside (ó, ñ etc.) but when it arrives to the c# back-end, "mensaje" is null:
public HttpResponseMessage PostMensaje(Mensajeria mensaje)
{
if (mensaje == null)
return
Request.CreateResponse(HttpStatusCode.InternalServerError, "El mensaje no
puede llegar al servidor");
But if httpPost in android app doesn't have any spanish characters, all is well and in the back-end "Mensajeria mensaje" "mensaje" is not null.
Why is null only for to carry spanish characters?.
With postman, all is well, with or without spanish chars.
I must yo say, my last attempt was to add web.config in web services .net:
<globalization
fileEncoding="ISO-8859-9"
requestEncoding="ISO-8859-9"
responseEncoding="ISO-8859-9"
/>
But the json when it reaches to the web service, "mensaje" is null (but it came out well of the android code). If JSON came out with "ó, ñ etc. "mensaje" in .net is null, otherwise, everything is perfect.
public HttpResponseMessage PostMensaje(Mensajeria mensaje)
{
try this:
httpPost.setHeader("content-type", "application/json;charset=utf-8" );
and
strHttpResponse = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");

Alternative for UrlEncodedFormEntity for sending data via POST

When sending the POST request using UrlEncodedFormEntity which takes List as input parameter along with the key, my request gets converted in the form of [key={json}] .
But the request i want to send should be in the form of key={json} , i.e not as List.
So, is there any alternative for the given method when using POST?
notes: webservice is working fine , and since it is json ,i cannot use Soap .
i ve tested it using POSTman and webservices are WCF(if thats of any use..)
if any code is required , please mention it.
Thanks in advance.
Edit code:
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(URL);
List<NameValuePair> value=new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("data",string));
//here it passes as List and here is where i want an alternate method
// by which i can send parameter as JSONobject
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(value);
request.setEntity(entity);
HttpResponse response = client.execute(request);
HttpEntity entity2 = response.getEntity();
if(entity2.getContentLength() != 0) {
Reader tapReader = new InputStreamReader(response.getEntity().getContent());
char[] buffer = new char[(int) response.getEntity().getContentLength()];
tapReader.read(buffer);
tapReader.close();
JSONObject tapJsonObj = new JSONObject(buffer);

How to send a JSON object over HttpClient Request with Android?

I want to send the JSON text {} to a web service and read the response. How can I do this from android? What are the steps such as creating request object, setting content headers, etc.
My code is here
public void postData(String result,JSONObject obj) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
String json=obj.toString();
try {
HttpPost httppost = new HttpPost(result.toString());
StringEntity se = new StringEntity(obj.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
Log.i("tag", temp);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
what mistake i have done plz correct me because it shows me an bad request error
but when i do post in poster it shows me status as Successfull 200 ok
I do this with
httppost.setHeader("Content-type", "application/json");
Also, the new HttpPost() takes the web service URL as argument.
In the try catch loop, I did this:
HttpPost post = new HttpPost(
"https://www.placeyoururlhere.com");
post.setHeader(HTTP.CONTENT_TYPE,"application/json" );
List<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("json", json));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpClient client = new DefaultHttpClient();
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
response = EntityUtils.toString(entity);
You can add your nameValurPairs according to how many fields you have.
Typically the JSON might become really huge, which I will then suggest gzipping it then sending, but if your JSON is fairly small and always the same size the above should work for you.
If it is a web service and not RestAPI call then, you can get the WSDL file from the server and use a SOAP Stub generator to do all the work of creating the Request objects and the networking code for you, for example WSClient++
If you wish to do it by yourself then things get a little tricky. Android doesn't come with SOAP library.
However, you can download 3rd party library here: http://code.google.com/p/ksoap2-android/
If you need help using it, you might find this thread helpful: How to call a .NET Webservice from Android using KSOAP2?
If its a REST-API Call like POST or GET to be more specific then its is very simple
Just pass a JSON Formatted String object in you function and use org.json package to parse the response string for you.
Hope this helps.

application/soap+msbin1 in android

I just need to send request to webservice via normal HTTP POST inorder to get response.I passed required parameter on body well.While i run it.,i got "Cannot process the message because the content type 'text/json' was not the expected type 'application/soap+msbin1'." error.When i made research over this.,due to "Web Service required the request to have a specific Content-Type, namely "application/soap+msbin1".When i replaced expected content type.,i got Bad Request error.I donno how to recover from that.
My code:
...
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler <String> resonseHandler = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("My URL");
postMethod.setHeader( "Content-Type", "text/json");
postMethod.setHeader( "Cache-Control", "no-cache");
JSONObject json = new JSONObject();
json.put("userName", "My Username");
json.put("password", "My Password");
json.put("isPersistent",false);
postMethod.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
HttpResponse response = httpClient.execute(postMethod);
...
It looks like you are trying to call WCF SOAP service. That service expects correct SOAP communication (= no JSON) and moreover it uses MS binary message encoding of SOAP messages (that is what content type describes) is not interoperable so I doubt you will be able to use it on Android device (unless you find implementation of that encoding for Java / Android).
HttpPost request = new HttpPost(url);
StringEntity entity = new StringEntity(json.toString());
entity.setContentType("application/json;charset=UTF-8"); entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
request.setHeader("Accept", "application/json");
request.setEntity(entity);
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
response = httpClient.execute(request);
}
Try using something like this. it worked for me.
Thanks.
N_JOY.

android server post data

I am new to android networking and would like to find the best solution/source that would help me learn the same. I have a working android application but i want to include network services that can get and send data to the webserver. While i was searching for the same i found link ( http://www.helloandroid.com/tutorials/connecting-mysql-database ) which dont produce any results. I also found that SOAP or REST (with android) are probably recommended methods, if so please give complete tutorials to learn the same ( i have no prior knowledge on webservices). In my application I would be required to send data to the server and receive data from the servers sql
Thank you
This is for post data on server,
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
// get response entity
HttpEntity entity = response.getEntity();
// convert entity response to string
if (entity != null)
{
InputStream is = entity.getContent();
// convert stream to string
result = convertStreamToString(is);
result = result.replace("\n", "");
}
or see how to post data to remote server in android app [closed], Post the data to Server

Categories

Resources