Я хочу подключить свое приложение Android к удаленному серверу MySQL базе данных.
Я просто хочу войти в систему и зарегистрироваться с помощью объекта JSON из PHP скрипт в приложение Android, но выдает ошибку org. json .JSONException: ':' <html><body><script at character 22(there is lots of data like a = toNumbers(unusual string) and my website url also here)...toHex...experies,etc...site require js to enable...</html>
Вот мой код для дескриптора HTTP-запроса:
public class RequestHandler {
public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams) {
URL url;
StringBuilder sb = new StringBuilder();
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
while ((response = br.readLine()) != null) {
sb.append(response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
//this method is converting keyvalue pairs data into a query string as needed to send to the server
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
А это мой php скрипт для подключения пользователей к android приложению
<?php
require_once 'config.php';
$response = array();
mysqli_set_charset($conn, 'utf8');
header("Content-Type: application/json; ");
if(isset($_GET['apicall']))
{
switch($_GET['apicall'])
{
case 'signup':
if(isTheseParametersAvailable(array('name','username','password'))){
$name = $_POST['name'];
$username = $_POST['username'];
$encode_password = $_POST['password'];
$password = password_hash($encode_password, PASSWORD_DEFAULT);
//$password = $_POST['password'];
$stmt = $conn->prepare("SELECT id FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows > 0){
$response['error'] = true;
$response['message'] = 'User already registered';
$stmt->close();
}else{
$stmt = $conn->prepare("INSERT INTO users (name, username, password) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $name, $username, $password);
if($stmt->execute()){
$stmt = $conn->prepare("SELECT id, name, username FROM users WHERE username = ?");
$stmt->bind_param("s",$username);
$stmt->execute();
$stmt->bind_result( $id, $name, $username);
$stmt->fetch();
$user = array(
'id'=>$id,
'name'=>$name,
'username'=>$username
);
$stmt->close();
$response['error'] = false;
$response['message'] = 'User registered successfully';
$response['user'] = $user;
}
}
}else{
$response['error'] = true;
$response['message'] = 'Required parameters are not available';
}
break;
case 'login':
if(isTheseParametersAvailable(array('username', 'password'))){
$username = $_POST['username'];
$password = $_POST['password'];
// $username = 'mahi@phone.com';
// $password = 'Mahi@123';
$stmt = $conn->prepare("SELECT id, name, username, password FROM users WHERE username = ?");
$stmt->bind_param("s",$username);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows > 0){
$stmt->bind_result($id, $name, $username, $password_hash);
$stmt->fetch();
if(password_verify($password,$password_hash))
{
$user = array(
'id'=>$id,
'name'=>$name,
'username'=>$username
);
$response['error'] = false;
$response['message'] = 'Login successfull';
$response['user'] = $user;
}
else
{
$response['error'] = false;
$response['message'] = 'Forget your password?';
}
}else{
$response['error'] = false;
$response['message'] = 'Invalid username or password';
}
}else{
$response['error'] = true;
$response['message'] = 'Invalid Operation Called';
}
break;
default:
$response['error'] = true;
$response['message'] = 'Invalid Operation Called';
}
}else{
$response['error'] = true;
$response['message'] = 'Invalid API Call';
}
echo json_encode($response);
function isTheseParametersAvailable($params){
foreach($params as $param){
if(!isset($_POST[$param])){
return false;
}
}
return true;
}
exit();
?>
Теперь вот моя страница регистрации
public class MainActivity extends AppCompatActivity {
EditText Name, Username, Password;
static TextView Info;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//if the user is already logged in we will directly start the profile activity
if (SharedPrefManager.getInstance(this).isLoggedIn()) {
finish();
startActivity(new Intent(this, ProfileActivity.class));
return;
}
Name = findViewById(R.id.et_reg_name);
Username = findViewById(R.id.et_reg_username);
Password = findViewById(R.id.et_reg_password);
Info = findViewById(R.id.tv_info);
findViewById(R.id.buttonRegister).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//if user pressed on button register
//here we will register the user to server
registerUser();
}
});
findViewById(R.id.textViewLogin).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//if user pressed on login
//we will open the login screen
finish();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
});
}
private void registerUser() {
final String name = Name.getText().toString().trim();
final String username = Username.getText().toString().trim();
final String password = Password.getText().toString().trim();
//first we will do the validations
if (TextUtils.isEmpty(name)) {
Name.setError("Please enter username");
Name.requestFocus();
return;
}
if (TextUtils.isEmpty(username)) {
Username.setError("Please enter your email");
Username.requestFocus();
return;
}
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(username).matches()) {
Username.setError("Enter a valid email");
Username.requestFocus();
return;
}
if (TextUtils.isEmpty(password)) {
Password.setError("Enter a password");
Password.requestFocus();
return;
}
//if it passes all the validations
class RegisterUser extends AsyncTask<Void, Void, String> {
private ProgressBar progressBar;
@Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("name", name);
params.put("username", username);
params.put("password", password);
//returing the response
return requestHandler.sendPostRequest(URLs.URL_REGISTER, params);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
//displaying the progress bar while user registers on the server
progressBar = findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//hiding the progressbar after completion
progressBar.setVisibility(View.GONE);
try {
//converting response to json object
JSONObject obj = new JSONObject("{"+s+"}");
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getInt("id"),
userJson.getString("name"),
userJson.getString("username")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
} else {
Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Info.setText(e.toString());
e.printStackTrace();
}
}
}
//executing the async task
RegisterUser ru = new RegisterUser();
ru.execute();
}
}
И еще одна вещь, которую я забыл добавить, - это я используя бесплатный веб-хостинг (infinityFree), на котором хранится моя база данных MySQL.