3

I am trying to develop a simple client-server application in Android. I have a problem while fetching a response from PHP code. It returns an HTML code instead of JSON. Is it a problem with the WAMP server I have used?

Here is the PHP code:

<?php
include_once './connect_db.php';
$db = new DBConnect();
$response = array();

$username = $_POST["username"];
$password = $_POST["password"];

if (empty($_POST['username']) || empty($_POST['password'])) 
{ 
    $response["success"] = 0; 
    $response["message"] = "One or both of the fields are empty.";
    die(json_encode($response));
}
$query = " SELECT * FROM account WHERE username = '$username'and password='$password'";
$sql1 = mysql_query($query); 
$row = mysql_fetch_array($sql1); 
if (!empty($row))
{ 
    $response["success"] = 1; 
    $response["message"] = "You have been sucessfully login"; 
    die(json_encode($response)); 
}
else
{ 
    $response["success"] = 0; 
    $response["message"] = "invalid username or password ";
    die(json_encode($response));
} 
mysql_close();
?>

login.java:

package com.example.rossh.register;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class login extends AppCompatActivity implements OnClickListener {
    private EditText user, pass;
    private Button login;
    JSONObject jsonObject;
    String response;
    // Progress Dialog
    private ProgressDialog pDialog;
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //setup input fields
        user = (EditText) findViewById(R.id.username);
        pass = (EditText) findViewById(R.id.password);

        //setup buttons
        login = (Button) findViewById(R.id.btnlogin);

        //register listeners
        login.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.btnlogin:
                String username = user.getText().toString();
                String password = pass.getText().toString();
                boolean cancel =false;
                View focusView = null;
                if(TextUtils.isEmpty(username))
                {
                    user.setError("This field is required!!");
                    cancel=true;
                    focusView=user;
                }
                if(TextUtils.isEmpty(password))
                {
                    pass.setError("This field is requird!!!");
                    cancel=true;
                    focusView=pass;
                }
                if(cancel)
                {
                    focusView.requestFocus();
                } else {
                    new AttemptLogin().execute(username, password);
                }
                break;

            default:
                break;
        }
    }

    class AttemptLogin extends AsyncTask<String, String, String> {
        /**
         * Before starting background thread Show Progress Dialog
         */
        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(login.this);
            pDialog.setMessage("Attempting login...");
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            // Check for success tag
            String username = args[0];
            String password = args[1];
                // Building Parameters
                final int success;
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", username));
                params.add(new BasicNameValuePair("password", password));

                Log.d("request!", "starting");
                // getting product details by making HTTP request
                JsonParser jsonParser = new JsonParser();

                jsonObject = jsonParser.makeHttpRequest(AppConfig.LOGIN_URL, "POST", params);
                if (jsonObject != null) {
                    try{
                        Log.d("Json data",">"+jsonObject);
                        success = jsonObject.getInt(TAG_SUCCESS);

                        if (success == 1) {
                            response = jsonObject.getString(TAG_MESSAGE);
                        } else {
                            Log.d("Login Failure!", jsonObject.getString(TAG_MESSAGE));
                            response = jsonObject.getString(TAG_MESSAGE);
                        }
                    } catch(JSONException e) {
                        e.printStackTrace();
                    }
                }
                return response;
            }

            /**
             * After completing background task Dismiss the progress dialog
             **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog once product deleted
                pDialog.dismiss();
                if (file_url != null) {
                    Toast.makeText(login.this, "ok", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}

jsonParser.java:

package com.example.rossh.register;

import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;
import android.widget.Toast;

public class JsonParser {
    InputStream is = null;
    static String json = "";
    static JSONObject jObj = null;

    // constructor
    public JsonParser() {
    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
        // Making HTTP request
        try {
            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));
                httpPost.setHeader("Content-Type","application/json");

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.d("String",">"+json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        // try parse the string to a JSON object
        try {
            JSONArray jsonarray = new JSONArray(json);
            jObj = jsonarray.getJSONObject(0);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing " + e.toString());
        }

        // return JSON String
        return jObj;
    }
}
5
  • Talk to your web developer on the same use postmen tool to verify the service Commented May 12, 2016 at 6:18
  • can you post here what you see in HTML code? Commented May 12, 2016 at 6:19
  • Best would be the raw data by curl -D - www.example.com on terminal console. Commented May 12, 2016 at 6:22
  • Instead of all this java code you should have posted that html. Commented May 12, 2016 at 6:57
  • Your question is unclear. What is the "html" that gets returned? How does the login page look like? Commented May 12, 2016 at 9:10

3 Answers 3

3

It may be due to one or more errors in your HTML, or if your page returns non-text objects. Make sure your HTML webpage does not throw an error while running from browser.

Sign up to request clarification or add additional context in comments.

Comments

2

For one thing I would suggest that your PHP script sets proper content type when returning json, see Returning JSON from a PHP Script. Also see Java HttpRequest JSON & Response Handling for how to do JSON requests in java.

Comments

1

Try changing die(json_encode($response)) to echo json_encode($response)

2 Comments

Then why did you accept this answer as correct? Very confusing.
@greenapps sorry i am new to this site :) :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.