如何将数据发送到PHP服务器并接收数据到Android
问题描述:
我在机器人编程新手,我想发送的数据到PHP服务器并接收数据的Android如何将数据发送到PHP服务器并接收数据到Android
展现,但我不知道创建它,我不是没有使用图书馆?并且可以举一些例子让我练习一下。
ps。对不起,我的英语不好。
例如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);
我想从EditText上发送keyword
和index
到PHP服务器并接收JSON数据显示列表视图。
答
HttpURLConnection类可用于获取,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) {
}
其中keyword
和index
将是你的EditText变量。
哦!对不起,我忘记告诉名称的PHP文件'“111.11.11/api.php”',不能使用'http:// xxxxxxx/webservice /&query =“....' –
好的,然后用111.11替换url .11/api.php?&query =“ + keyword.getText()。toString() +”&index =“+ index.getText()。toString()) –
我得到错误行'return null'无法返回值形成一个void结果类型的方法。 –