我是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);
我想将 keyword
和 index
从 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) {
}
keyword
和 index
将是您的 EditText 变量。
关于java - 如何向php服务器发送数据和向android接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44344701/