您可以使用 GET 或 POST 方法将数据传递到 PHP 文件。
Get 方法是传递简单数据的简单方法。使用 GET 您可以将变量添加到 URL
例子:
192.168.1.123/myproject/uploads/treatphoto.php?myVariable1=MyContent&myVariable2=MyContent2
在 PHP 中:
$content1 = $_GET['myVariable1'];
$content2 = $_GET['myVariable2'];
“MyContent”的内容也需要是字符串编码的。使用任何 UrlEncoder。
要使用此方法传递 byte[] 数组,您需要将 byte 数组转换为以某种可打印编码(如 base64)编码的字符串
GET 方法还有一个可以安全传递的数据的排序限制(通常为 2048 字节)
另一种方法“POST”更复杂(但不是很多),用于添加更多数据。
您需要准备 HttpConnection 以将数据作为 POST 传递。
此外,存储在 urlParamenters 中的数据需要根据 url 编码。
使用 post 传递数据类似于 GET,但不是在 url 旁边添加所有变量,而是将变量添加到 httpConnection 请求的 Stream 中。
java代码示例:
String urlParameters = "myVariable1=myValue1&myVariable2=myValue2";
HttpURLConnection connection = null;
try {
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
// Use post and add the type of post data as URLENCODED
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// Optinally add the language and the data content
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
// Set the mode as output and disable cache.
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
// Get Response
// Optionally you can get the response of php call.
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
php类似,只需要将$_GET替换为$_POST即可:
$content1 = $_POST['myVariable1'];
$content2 = $_POST['myVariable2'];