Android - Php receive string from android

903

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 !!

407

Answer

Solution:

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);
?>
181

Answer

Solution:

There are many tutorials online for this kind of stuff:

try {

        String url = "http://yoursiteurlhere.com" ;

        URL myURL = new URL(url);

        HttpURLConnection httpURLConnection = (HttpURLConnection) myURL.openConnection();

        httpURLConnection.setRequestMethod("POST");

        String body = params[0];

        httpURLConnection.setRequestProperty("Content-Type", "application/json");
        httpURLConnection.setRequestProperty("Accept", "application/json");
        httpURLConnection.setDoOutput(true);
        httpURLConnection.connect();

        DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
        wr.writeBytes(body);
        wr.flush();
        wr.close();

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

        String inputLine;
        stringBuffer = new StringBuffer();

        while((inputLine = bufferedReader.readLine()) != null){
            stringBuffer.append(inputLine);
        }

        bufferedReader.close();

        return stringBuffer.toString();
    }catch (MalformedURLException e){
        e.printStackTrace();
    }catch (IOException e){
        e.printStackTrace();
    }

Remember though to do this in a background thread!

Please refer to this for example.

People are also looking for solutions to the problem: php - header() works with wamp but not on server

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.