java - 如何向php服务器发送数据和向android接收数据

标签 java android

我是android编程的新手,我想将数据发送到php服务器并接收数据以在android中显示

但我不知道要创建它,我不会不使用库吗?并且可以举一些例子让我练习。

附言。对不起,我的英语不好。

示例 Myphp "xxx.xxx.x.x/api.php"

$keyword = $_GET['keyword'];
$index= $_GET['index'];
$path = "http://xxxxxxx/webservice/&query=".urlencode($keyword)."&index=".$index."";
            $jsondata = file_get_contents($path);
            $jsons = json_decode($jsondata,true);

            echo json_encode($jsons);

我想将 keywordindex 从 edittext 发送到 php 服务器并接收 json 数据以显示 ListView 。

最佳答案

HttpURLConnection 可用于获取、放置、发布、删除请求:

try {
                // Construct the URL
    URL url = new URL("http://xxxxxxx/webservice/&query="
    +keyword.getText().toString()
    +"&index="+index.getText().toString());
    // Create the request 
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();
    // Read the input stream into a String
            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                // Nothing to do.
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                // But it does make debugging a *lot* easier if you print out the completed
                // buffer for debugging.
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                // Stream was empty.  No point in parsing.

            }
            JsonStr = buffer.toString(); //result
} catch (IOException e) {
 }

keywordindex 将是您的 EditText 变量。

关于java - 如何向php服务器发送数据和向android接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44344701/

相关文章:

java - Play Scala 从另一个方法调用 Controller 方法

java - Spring Integration 4.2 中 application/json 响应被转义的问题

android - 在 Android 中拖放 API 级别 10

android - 使用 Gradle 在 Android 项目中混合使用 Java+Scala 的最简单方法是什么?

java nio套接字未检测到机器何时进入休眠或 hibernate 状态

java - 监控java中的进程

java - 扫描带注释的类不适用于 Instant Run

android - 安装适用于 Android 的 Maps SDK 实用程序设置 (android-maps-utils) 时出现问题

java - 应用程序在设备/模拟器中运行时崩溃

android - 自定义形状的 TextView ,Android