killertoge killertoge - 4 months ago 31
PHP Question

Android - Php receive string from android

I have following PHP-Script:

<?php
$parameter=$_POST['uploaded_text'];

$data = $parameter.PHP_EOL;
$fp = fopen('uploads/test.txt', 'a');
fwrite($fp, $data);

?>


How can I give to
$parameters
a string value from android device ?
I was looking for tutorials with HttpURLConnection but I only find 'HttpClient' which I can't use still.
Could someone tell me how I could simply do it ?
thanks in advance !!

Answer

My suggestion is to take a look at StringRequests. Here is an example of how to send things to a PHP file, which updates a database, or can do whatever:

LoginRequest.java:

package com.example.your_app.database_requests;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

import java.util.HashMap;
import java.util.Map;

public class LoginRequest extends StringRequest {

    private static final String LOGIN_REQUEST_URL = "http://example.com/Login.php";
    private Map<String, String> params;

    public LoginRequest(String username, String password, Response.Listener<String> listener) {
        super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
        params = new HashMap<>();
        params.put("username", username);
        params.put("password", password);
    }

    @Override
    public Map<String, String> getParams() {
        return params;
    }

}

To send the StringRequest and get a return value:

Response.Listener<String> listener = new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);

                        boolean success = jsonResponse.getBoolean("success");
                        // Anything else that your php file returns will go here (like the boolean success)

                        if (!success) {
                            Log.e(TAG, "Could not login.");
                        } else {
                            Log.e(TAG, "Logged in.");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };
            LoginRequest loginRequest = new LoginRequest(username, password, listener);
            RequestQueue requestQueue = Volley.newRequestQueue(context);
            requestQueue.add(loginRequest);

Login.php:

<?php

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

    $con = mysqli_connect("website.com", "dbusername", "dbpassword", "dbtable");

    $response = array();
    $response["success"] = false;

    /* Do something */

    $response["success"] = true;

    echo json_encode($response);
?>
Comments