How to send plain text file to php using openConnection () method

When I search for sending plain text from an android file to a file php, I find examples that they use obsolete classes and packages, such as org.apache.httpetc. And google recommends using the method openConnection()in the URL class .

But when I look for the URL class and class URLConnectionclass and HttpUrlConnection, I cannot find methods for sending plain text to the php file. Please know me.

0
source share
1 answer

Well, you can create a class like this:

HttpURLConnectionHandler.java

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionHandler
{
     protected String urlG = "http://192.168.43.98/yourdirectory/";
    public String sendText(String text)
    {
    try {
        URL url = new URL(urlG+"receiveData.php");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");

        // para activar el metodo post
        conn.setDoOutput(true);
        conn.setDoInput(true);
        DataOutputStream wr = new DataOutputStream(
                conn.getOutputStream());
        wr.writeBytes("mydata="+text);
        wr.flush();
        wr.close();

        InputStream is = conn.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        return response.toString();
    }
    catch(Exception e){ return "error";}
    }

}

and you can create an object where you want

HttpURLConnectionHandler handler= new HttpURLConnectionHandler();
String response = handler.sendText("this is a text");

and receiveData.php:

 <?php
    // the received string
    $received = $_POST['mydata'];
    // you send a response to android
    echo "no hay registros";
 ?>

you may notice that the text is sent to String var

0

All Articles