here i´m in my first post. I´m getting started to android.
I trying to connect my app to a webservice throu a tutorial from mybringback, but i´m getting an error with my json return.
09-12 15:54:06.717: E/JSON Parser fallha(8254): Error parsing data org.json.JSONException: End of input at character 0 of
I already found the reason, it´s happen becouse It´s returning the HTML from my php page instead json. When i tried set a fix string with my json it worked.
When i try to get the json from the browser it works fine.
I set a Log.d in the reader and i got this:
09-12 15:35:10.807: D/Acha Erro POR FAVOR(6691): <h1>Login</h1>
09-12 15:35:10.807: D/Acha Erro(6691): <form action="login.php" method="post">
09-12 15:35:10.807: D/Acha Erro(6691): Username:<br />
09-12 15:35:10.807: D/Acha Erro(6691): <input type="text" name="username" placeholder="username" />
09-12 15:35:10.807: D/Acha Erro(6691): <br /><br />
09-12 15:35:10.807: D/Acha Erro(6691): Password:<br />
09-12 15:35:10.807: D/Acha Erro(6691): <input type="password" name="password" placeholder="password" value="" />
09-12 15:35:10.807: D/Acha Erro(6691): <br /><br />
09-12 15:35:10.807: D/Acha Erro(6691): <input type="submit" value="Login" />
09-12 15:35:10.807: D/Acha Erro(6691): </form>
09-12 15:35:10.807: D/Acha Erro(6691): <a href="register.php">Register</a>
I´ve spent about 3 days trying to find out a way to solve that.
Following my two classes and php
package com.example.testemysql;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.LogRecord;
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.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
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 MainActivity extends Activity implements OnClickListener{
private EditText user, pass;
private Button mSubmit, mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script location:
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/login.php";
//testing on Emulator:
private static final String LOGIN_URL = "http://www.bazarsol.6te.net/ANDROID/login.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
//JSON element ids from repsonse of php script:
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_main);
//setup input fields
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
//setup buttons
mSubmit = (Button)findViewById(R.id.login);
mRegister = (Button)findViewById(R.id.register);
//register listeners
mSubmit.setOnClickListener(this);
mRegister.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
break;
case R.id.register:
//Intent i = new Intent(this, Register.class);
//startActivity(i);
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(MainActivity.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("URL",LOGIN_URL);
Log.d("PARAMETROS",""+ params);
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
//Log.d("Login Successful!", json.toString());
Log.d("Login Successful!", "");
//Intent i = new Intent(Login.this, ReadComments.class);
finish();
//startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* 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(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
JSONParser
package com.example.testemysql;
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.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// 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));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
Log.d("Acha o erro POR FAVOR ajuda",""+ httpResponse);
}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, "iso-8859-1"), 8);
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
Log.d("Acha Erro POR FAVOR",""+ reader.readLine());
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.d("Acha Erro", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e);
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser fallha", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
PHP - UPDATED
<?php
//load and connect to MySQL database stuff
require("config.inc.php");
//gets user's info based off of a username.
$query = "
SELECT
indice,
usuario,
senha
FROM usuarios
WHERE
usuario = :username
";
$query_params = array(
':username' => $_POST["username"]
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
print_r($_REQUEST);
print_r (var_dump($_POST));
print_r(get_headers());
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!2";
echo "Bruno 2";
die(json_encode($response&$ex));
}
//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$validated_info = false;
//fetching all the rows from the query
$row = $stmt->fetch();
if ($row) {
//if we encrypted the password, we would unencrypt it here, but in our case we just
//compare the two passwords
if ($_POST["password"] === $row["senha"]) {
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if ($login_ok) {
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
} else {
$response["success"] = 0;
$response["message"] = "Invalid Credentials!";
die(json_encode($response));
}?>
RESULTS
09-16 16:58:00.687: D/Acha o erro POR FAVOR ajuda(29176):org.apache.http.message.BasicHttpResponse@42680990
09-16 16:58:00.687: D/Acha Erro POR FAVOR(29176): Array
09-16 16:58:00.687: D/Acha Erro(29176): (
09-16 16:58:00.687: D/Acha Erro(29176): )
09-16 16:58:00.687: D/Acha Erro(29176): array(0) {
09-16 16:58:00.687: D/Acha Erro(29176): }
09-16 16:58:00.687: D/Acha Erro(29176): {"success":0,"message":"Invalid Credentials!"}
In your request, you should specify that the desired return is of type Json.
You may need to add something similar to the following to your HTTP Request Header:
header('Content-Type: application/json');
In your code, I'd recommend something like this:
// 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();
looks like your issue is in your filtering, never ever ever do string comparisons with ==, it doesn't work.
instead of doing this line:
if(method == "POST"){
//...
else if(method == "GET")
do this:
if (method.equals("POST"))
//...
else if(method.equals("GET"))
this is causing your post value to be sent to the server empty. thats the only reason your php script will ever output the login form instead of processing the JSON request... of course after you get past this issue, there may be other bugs to look into..
You get the inlog page. So aparently you have to use a username and pass before your request is honored. With the browser you first logged in?
Ok i see in the php script that that html is returned when $_POST is empty. So you should POST better.
After all, i got a solution, the problem wasnt the code it was the server (6te.net) settings. I tried in a local xampp server and it worked fine.
Thanks to every body, especialy to greenapps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.