Error Android - received HTML instead of JSON - android

I'm working on a Android application and I'm trying to get a JSON response from a server which is configured to return a json object (".../current_user.json") when receives a GET message, but the answer I get is in HTML format and not in JSON format as expected.
I don't understand why is this happening because I did the same requests on the browser and with the program RESTClient and got the right answer in JSON format.
Here is the code I'm using.
JSONObject json = new JSONObject();
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(params, 10000);
HttpClient httpClient = new DefaultHttpClient(params);
HttpGet get = new HttpGet(url_getiduser);
HttpResponse response = httpClient.execute(get);
String sresponse = "error";
Log.d("url get", url_getiduser);
Log.d("pedido get", get.getMethod());
if(response != null)
{
InputStream in = response.getEntity().getContent();
sresponse = convertStreamToString(in);
Log.d("resposta http", sresponse);
if(!sresponse.equals("error"))
{
JSONObject object = new JSONObject(sresponse);
id_user = (String) object.get("id");
json = object;
Log.d("objecto json", object.toString());
}
else Log.d("Error on json parser", sresponse);

There are few cases where you get HTML text
You might have called a wrong function which gives a 404 page.
Might be a database error on server side where you will get database error message
Server might be sending a styled data which has HTML tags
But you better Log the response and paste it here.

Related

How to POST list of objects as JSON from Android client to PHP REST API?

Scenario:
REST API: PHP Slim Framework
Android HTTP client library: loopj
I am storing an ITEM as json string in sqlite.
I want to POST this JSON on server. Each item is a record in my SQLite database.
What I am currently doing?
I have JSON with list of objects. I want to POST it to my PHP based REST API.
Here is the code
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
Item item = new Item();
try {
item.setOfflineId(Long.parseLong(cursor.getString(0)));
item.setName(cursor.getString(1));
item.setImageLocalPath(itemPayload.getImageLocalPath());
item.setToUpdate(Boolean.parseBoolean(cursor.getString(3).toString()));
item.setDeviceID(cursor.getString(4));
item.setCreatedDate(cursor.getString(5));
//item.setImageBlob(cursor.getBlob(5));
String imageURL = itemPayload.getImageLocalPath();
File imageFile = new File(imageURL);
} catch (Exception e) {
Log.d("Ex", e.getMessage().toString());
}
itemList.add(item);
} while (cursor.moveToNext());
}
}
}catch(SQLException ex){
Log.d("DB", ex.getMessage().toString());
}
The challenge?
When I put the params for post, I also set one Param to File as I want to upload an image file as well. I know how to send one object as JSON. I want to POST the list of items (items having image Files). How to achieve this?
One way is that I do an API POST for each object in the list. Not sure if it is a good way to do it.
Looking for advice.
You can post json using this way
JSONObject json = new JSONObject();
json.put("obj", "obj value");
StringEntity entity = new StringEntity(json.toString());
client.post(context, url, entity, "application/json",
responseHandler);
Use this code to send Json data
try{
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("projectid","1");
jsonObject.accumulate("cnumber", "8983899383");
jsonObject.accumulate("address","IN");
jsonObject.accumulate("companyid","5");
jsonObject.accumulate("uploadimage","");
jsonObject.accumulate("id","9")
data = jsonObject.toString();
Log.d("json data",data);
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(CHECK_WEBSERVICE_URL);
StringEntity se = new StringEntity(data);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();

Recieving HTML file as responce instead of JSON Object through get request

I am developing an android app where user logs on to his/her account. After logging in I will receive XSRF token and Laravel Session Id to recognise the specific user. I have to send these tokens for every request I send to the API's to get the appropriate information. But when I am sending the required details as shown in the image, I am getting HTMl file as response instead of getting JSON Object. I was seriously stuck at this problem. Correct Solution may take forward the whole app.
class RegisterConnection extends AsyncTask<String,String,JSONObject> {
protected JSONObject doInBackground(String... arg0) {
JSONObject output = new JSONObject();
DefaultHttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 5000); //Timeout Limit
HttpResponse response = null;
try {
HttpGet get = new HttpGet(statsURL);
get.setHeader("Accept", "application/json");
CookieStore store = new BasicCookieStore();
BasicClientCookie cookie1 = new BasicClientCookie("XSRF-TOKEN", XSRF);
BasicClientCookie cookie2 = new BasicClientCookie("laravel_session", laravel);
store.addCookie(cookie1);
store.addCookie(cookie2);
client.setCookieStore(store);
response = client.execute(get);
if(response!=null){
InputStream in = response.getEntity().getContent();
String resultstring = Utilities.convertStreamToString(in);
Log.i("Result1", resultstring);
output = new JSONObject(resultstring);
Log.i("Result2", output.toString());
}
} catch(Exception e) {
e.printStackTrace();
try {
output.put("sai","error");
Log.i("MainActivity", output.toString());
} catch (JSONException e1) {
e1.printStackTrace();
}
return output;
}
return output;
}
These are the server requirements
http://imgur.com/OY9Q673
This is the Output received
http://imgur.com/IB5AEcT
As far as I can tell, there is nothing wrong with your Android client code.
You are getting HTML from the server so the main reason could be that your Laravel server is rendering the views and sending you back html instead of JSON. Instead of rendering the views on the server, you should send JSON response on your Laravel server side.
Add Jsoup dependency in your gradle file
implementation 'org.jsoup:jsoup:1.11.2'
Document document = Jsoup.parse("http://imgur.com/IB5AEcT");
Elements el = doc.select("button");
Log.i("..........",""+el.attr("data-invite-details"));
Jsoup tutorial
http://jsoup.org/apidocs/org/jsoup/Jsoup.html

Android calling webservice issue

i am calling webservice in this way..
public static String POST(String url, ArrayList<ModelLatLog> list,Context con){
InputStream inputStream = null;
String result = "";
AppLog.logString(TAG+"URL : "+url);
AppLog.logString(TAG+"ListSize: "+list.size());
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String json = "[";
for(int j=0;j<list.size();j++){
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("DId", ""+list.get(j).get_idDevice());
jsonObject.accumulate("Lat", ""+list.get(j).getLat());
jsonObject.accumulate("Long", ""+list.get(j).getLong());
jsonObject.accumulate("DIn", ""+list.get(j).getDt());
jsonObject.accumulate("TIn", ""+list.get(j).getTm());
jsonObject.accumulate("Dce", ""+list.get(j).getDce());
if(j==0 ){
json = json+""+jsonObject.toString();
AppLog.logString(TAG+"if j: "+j);
}
else{
json = json+","+jsonObject.toString();
AppLog.logString(TAG+"else j: "+j);
}
}
json = json+"]";
AppLog.logString(TAG+"JSON: "+json);
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpclient.execute(httpPost);
int resopnceStatus = httpResponse.getStatusLine().getStatusCode();
AppLog.logString(TAG+"set data resopnceStatus: "+resopnceStatus);
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
e.printStackTrace();
AppLog.logString("InputStream"+ e.getLocalizedMessage());
}
return result;
}
AppLog is nothing it's log.d
it's giving me error like
11-19 18:15:39.088: I/Service(32261): Utility: set data resopnceStatus: 500
11-19 18:15:39.096: I/Service(32261): result: <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><soap:Fault><soap:Code><soap:Value>soap:Receiver</soap:Value></soap:Code><soap:Reason><soap:Text xml:lang="en">Server was unable to process request. ---> Data at the root level is invalid. Line 1, position 1.</soap:Text></soap:Reason><soap:Detail /></soap:Fault></soap:Body></soap:Envelope>
Looks like the webservice is returning you an error, so the HTTP POST call actually worked.
Are you sending it the correct format? looks like its expecting XML request and you send JSON.
Why you are Taking so burden...
Just use volley service...It will take care of every thing...
Just use StringRequest in Volley..your task will be easy...
Download volley example here
If you haven't already figure out your problem, I believe ksoap2 is more intuitive for dealing with webservices on android, this link has a good example on it.
is there clear Example of Android ksoap2 returning array of objects from .Net Web service?

Trouble sending JSON Post Android

It has been a while since I programmed for Android and I have lost all my previous work which had the code in it I am having problems with. I am developing an app for both Android and iPhone which connect to the same server to download data. All is well in the iPhone version but on Android when I hit the server with the post data containing the method name I would like to to run on the server it seems that the data is not added to the request.
Why is the POST not working in this request for Android but does for the iPhone version of the app?
Here is the code I am using:
public static void makeRequest() throws Exception {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
HttpEntity entity;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost("http://divisi.co.uk/rest/requesthandler.php");
json.put("method", "getEventListData");
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
entity = response.getEntity();
String retSrc = EntityUtils.toString(entity);
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
if(result.getString("SC") == "200"){
JSONArray data = result.getJSONArray("data");
}
else{
}
} catch(Exception e) {
e.printStackTrace();
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
The response I get mack from the server is:
{"data":{"scalar":""},"SC":405,"timestamp":1363788265}
Meaning the method name was not found, i.e. not posted in my request to the server.
heres an example of how i do things like this:
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://divisi.co.uk/rest/requesthandler.php");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart(new FormBodyPart("method", new StringBody("getEventListData")));
reqEntity.addPart(new FormBodyPart("NEED_A_KEY_HERE", new StringBody("" + json.toString())));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
JSONObject responseDict = new JSONObject(EntityUtils.toString(response.getEntity()));
allow this is your "http://divisi.co.uk/rest/requesthandler.php" page code, then in android you can use this... you don't allow post in your URL,
use fiddler on your sever side. see if the http message is correct. it seems your sever side problem, can you show us your sever side code which receive and parse json.
If the server can't read your request try to remove:
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
It will use the mime type defaults HTTP.PLAIN_TEXT_TYPE i.e. "text/plain".
I don't see any other possibility, if your code is the one you posted and not a more complicated input JSON object.
Your code to set the POST body may be just fine. I think the problem may be with your web service. Try using something like Rested or curl to manually make the call to your server. I made exactly the same request you are making, including with and without the POST body, and I got the same response from your server:
{"data":{"scalar":""},"SC":405,"timestamp":1365704082}
Some things that may be tripping you up:
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
if(result.getString("SC") == "200"){
JSONArray data = result.getJSONArray("data");
}
Here, you are comparing the string "405" to "200" using ==, when you should first do a null check and then use .equals("200") instead. Or, use result.getInt("SC") == 200 since this is an integer type in your response JSON.
Also, the "data" entity from your server response is not actually coming back as a JSON array. You should use getJSONObject("data") instead.
Additionally, it's always a good idea to externalize your strings.
Here's how the code should look:
public static final String JSON_KEY_SC = "SC";
public static final String JSON_KEY_DATA = "data";
...
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
String sc = result.getString(JSON_KEY_SC);
if (sc != null && sc.equals("200")) {
JSONObject data = result.getJSONObject(JSON_KEY_DATA);
}
else {
...
}

How can i convert the string with special characters into json object

Hi i am trying to parse the string and convert it in to JSONObject.But it is not converted and giving the error like
"07-28 11:36:47.674: WARN/System.err(6050): org.json.JSONException: Unterminated string at character 3136 of {"data":[{""...."(there is my data)
First i thought there is some special characters like ~,#,%,& and replace the characters with " " but there is no result and giving the same error.
And i modified the web services data by encoding with UTF-8 format. and i used the code to get decode the UTF-8 formatted data in my application.here is my code:
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
params.setBooleanParameter("http.protocol.expect-continue",false);
HttpClient httpclient = new DefaultHttpClient(params);
HttpGet httpget =new htpGet("http://www.mylink.com"+todaydate);
try
{
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
jsonText = EntityUtils.toString(entity, HTTP.UTF_8);
Log.d("TEST", jsonText); /this is the result string
}
catch (Exception e)
{
}
JSONObject jObj = new JSONObject(jsonText.toString());
Here i cannot convert the string(jsonText) into json object(jobj).But in logcat it is displaying the string jsonText perfectly. Is there any suggestion to get the data as json object.
I need to use the Json object in my application.
If you are certain that the JSON data is valid and no special characters are causing problems then "Unterminated string at character" could mean that you have not received the whole string.
You could prove this by checking a substring from the end and displaying that in logcat
If not then you need to start looking for the special characters again

Categories

Resources