Roshan Sharma Roshan Sharma - 6 months ago 46
Java Question

Http post request return HTML code instead of json data

I am tired to find what actually have gone.i am tring to develop simple client-server application in android.But i got problem while fetching response from php code. It returns HTML code instead of json .is it problem of wamp server i have used?

Here 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 is:

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 is:

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;

}
}

Answer

Change from die(json_encode($response)) to echo json_encode($response)

Comments