如何使用openConnection()方法将简单文本发送到php文件

时间:2015-07-21 19:26:08

标签: android

当我搜索从android发送简单文本到php文件时,我发现他们使用已弃用的类和包org.apache.http等等的示例。 谷歌建议我们在网址类中使用openConnection()方法。

但是当我搜索 URL 类和URLConnection类和HttpUrlConnection类时,我找不到将简单文本发送到php文件的方法。请注意我。

1 个答案:

答案 0 :(得分:0)

好吧,你可以创建一个这样的类:

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";}
    }

}

您可以在任何地方创建对象

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

和receiveData.php:

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

您可以注意到文本是在String var

中发送的