android - How can I send a simple text to php file using the openConnection () method -


when search sending simple text android php file find examples use deprecated classes , packages such org.apache.http , etc. , google recommends use openconnection() method in url class.

but when search url class , urlconnection class , httpurlconnection class, can not find methods send simple text php file. please aware me.

well, create class 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 = 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 can create object wherever want

httpurlconnectionhandler handler= new httpurlconnectionhandler(); string response = handler.sendtext("this text"); 

and receivedata.php:

 <?php     // received string     $received = $_post['mydata'];     // send response android     echo "no hay registros";  ?> 

you can notice text sent in string var


Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -