如何将数据发送到PHP服务器并在Android上接收数据

3
我是一名Android编程新手,希望将数据发送到PHP服务器并接收数据以在Android中显示。但我不知道如何创建它,也不知道如何使用库?您能给我一些实践的例子吗?
注:抱歉我的英语不好。
例如,我的PHP为“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);

我希望从EditText中发送关键字索引到PHP服务器,并接收JSON数据以显示ListView。

1个回答

0

HttpURLConnection 可用于 get、put、post、delete 请求:

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变量。


哦!抱歉,我忘记告诉您 PHP 文件的名称是 "111.11.11/api.php",无法使用 http://xxxxxxx/webservice/&query=".... - ARR.s
好的,然后将URL替换为111.11.11/api.php?&query=" + keyword.getText().toString() + "&index=" + index.getText().toString() - Nihal Saxena
我得到了错误行return null,无法从具有void结果类型的方法返回值。 - ARR.s
connect() 是多余的。输入流不能为 null,因此测试它是毫无意义的。异常应该传播给调用者,而不是被吞噬。 - user207421
@EJP,你能给我举个例子吗?或者告诉我应该用哪个库? - ARR.s

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接