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

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

Related

How to make a web request sending a HASH key and get a Response Android

I've searched everywhere on how to make this happen but with no results.
First I need to make a request to a website then send a hash (which I already have) and get a response with some data.
I was able to connect but I'm not able to use the hash key to get the data.
Can anyone help me how to do this using android?
Thanks.
I tried to follow this:Make an HTTP request with android
using a host
The solution:
final HttpClient client = new DefaultHttpClient();
final HttpPost postMethod = new HttpPost(URL);
postMethod.setEntity(new StringEntity(postData, "utf-8"));
String responseData = "";
try {
final HttpResponse response = client.execute(postMethod);
responseData = EntityUtils.toString(response.getEntity(), "utf-8");
} catch(final Exception e) {
// handle exception here
}
This is an example of what you can do:
final String URL = "http://192.168.0.100:8000/myHistory/mobile/?user=";
HttpClient client;
StringBuilder url = new StringBuilder(URL);
url.append(user);
url.append("&pwd=");
url.append(hash);
client = new DefaultHttpClient();
HttpGet get = new HttpGet(url.toString());
HttpResponse response = null;
try {
response = client.execute(get);
} catch (IOException e) {
e.printStackTrace();
}
int status = 0;
status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = "";
try {
data = EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
}
//Here you manipulate the 'data' variable, which is in HTML format.
It depends on which kind of hash you are using (SHA-N, MD5, etc) and the kind of framework you are using to build the server. Try to search on the documentation of your framework which kind of cryptographic hash function is used. Then search on internet an API that implements this cryptographic hash function on your code (e.g., Django uses PBKDF2). After that, you need to define the parameters of this function (salt, number of iterations, password (or hash)). The algorithm calculates the hash (password) using the salt and number of iterations values. So when you are trying to access a server you have to send via HTTP the hash that was generated. If this hash is the same hash generated on the server side, then the authentication is successful.

Sending POST json from Android and receiving on Django

I am trying to get an android app to interact with a server in Django.
The app is trying to POST "json" data to Django. However, I am unable to receive the object on the Django end.
The value of request.POST is <QueryDict: {}> although the data sent isn't blank. Following is the code snippet for POST request from android.
public static String POST(String url,JSONObject obj){
InputStream inputStream = null;
String result = "";
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String json = obj.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type","application/json");
HttpResponse httpResponse = httpClient.execute((HttpUriRequest)httpPost);
inputStream = httpResponse.getEntity().getContent();
if(inputStream!=null){
result = convertInputStreamToString(inputStream);
}else{
result = "Did not work!";
}
}catch(Exception e){
}
return result;
}
EDIT:
Earlier, I was getting CSRF error and handled it this way (I haven't worked with Django enough to know if this is correct way to handle CSRF error)
#csrf_exempt
def search(request):
logger.debug(request.POST)
"""Code for JSON object processing"""
Any help with rectifying the problem would be highly appreciated.
OK I'm not very fluent in java but it seems to me that your request is well formed.
I think the issue is that you are sending the data as a json string instead of as if it was a raw form. When you do it this way, the data is not displayed in request.POST but in request.body as what it is: a json string, not form-like data.
So I think you have to take one of these ways:
send the data from the Android app as a form (not json-like). This way you'll see it in request.POST or
translate request.body into a dict and work with it instead of request.POST
Hope this helps! :)

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 {
...
}

Error Android - received HTML instead of JSON

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.

How can I capture a response sent from android to Django server using views.py?

I am new to the client-server side programming so my question might be basic.
Basically, I am trying to send data in JSON format from android to a Django server. The code for sending the data is the following:
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:8000/androidweb/edit/");
JSONObject j = new JSONObject();
try {
j.put("name", "cdfe");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
nameValuePairs.add(new BasicNameValuePair("year", j.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}catch(Exception e) {
//catch the exception and print it
}
So my intention is to basically call the url mentioned in code. I added the url to Django urls.py so I can use the views.py class to store the JSON data I entered above in a sqlite database table, which contains only one field called "name". However, I don't know if my approach is right. Most code samples I have seen pass the data to a php file, so I was wondering if it is possible to do it through a python class, views.py?
If it is possible, can you please give me a code sample to be implemented in "views.py" of how to capture JSON data sent from the above code and store it in a table with a "name" field?
Thanks!
Data sent via POST is available via request.POST. Try examining request.POST['year'].

Categories

Resources