Java – HTTP post requests return HTML code instead of JSON data

HTTP post requests return HTML code instead of JSON data… here is a solution to the problem.

HTTP post requests return HTML code instead of JSON data

I’m trying to develop a simple client-server application in Android. There was a problem getting the response from PHP code. It returns HTML code instead of JSON. Is there a problem with the WAMP server I use?

This is 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;
    }
}

Solution

This could be due to one or more errors in your HTML, or your page returning a non-text object. Make sure that your HTML web page doesn’t throw errors when running from a browser.

Related Problems and Solutions