0
我想从我的android应用程序发送数据到我的php代码并检索它,但是当我在我的网站上打印值时,它们显示值为空。一些我曾尝试为Android的例子是:从android发送数据到php并检索它
OutputStream os = null;
InputStream is = null;
HttpURLConnection conn = null;
try {
//constants
URL url = new URL(tempURL);
JSONObject jsonObject = new JSONObject();
jsonObject.put("message", "message");
jsonObject.put("password", "password");
String message = jsonObject.toString();
Toast.makeText(this, "message = " + message, Toast.LENGTH_SHORT).show();
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /*milliseconds*/);
conn.setConnectTimeout(15000 /* milliseconds*/);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(message.getBytes().length);
//make some HTTP header nicety
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
//open
conn.connect();
//setup send
os = new BufferedOutputStream(conn.getOutputStream());
os.write(message.getBytes());
//clean up
os.flush();
//do something with response
is = conn.getInputStream();
//String contentAsString = readIt(is,len);
} catch (IOException | JSONException e) {
e.printStackTrace();
} finally {
//clean up
try {
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
}
另一条是:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://samplewebsite.com/welcome.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<>(2);
nameValuePairs.add(new BasicNameValuePair("state", "state"));
nameValuePairs.add(new BasicNameValuePair("tag", "tag"));
Toast.makeText(this, "nameValuePairs = " + nameValuePairs, Toast.LENGTH_LONG).show();
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
// msgTextField.setText(""); // clear text box
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
一些我已经在PHP尝试的代码是:
print_r("tag = " + $_POST['tag']);
而且
$json = file_get_contents('php://input');
$obj = json_decode($json);
$tag = $obj->{'tag'};
$state = $obj->{'state'};
请帮助我,这些考试都没有ples为我制定了。任何解决方案都会有帮助。谢谢!
你是否在任何地方托管你的PHP代码?你有什么错误吗?我不知道你是否在使用另一个线程,但对于初学者来说,如果你不把它放在后台线程上,你的应用程序应该会崩溃。 – Rafa
向我们展示了如何在'welcome.php'中处理帖子 –
您应该使用REST控制台在Android以外的第一个地方进行测试,以便知道它在服务器端运行。之后,您可以调试客户端。 –