【问题标题】:How to post a named variable to a PHP file?如何将命名变量发布到 PHP 文件?
【发布时间】:2011-08-17 06:42:32
【问题描述】:

我想通过使用 HttpConnection 东西将 String 变量发布到 PHP 文件中。第一个数据是从记录存储返回的 byte[] 数据。所以应该单独发。那么如何发布 String 变量呢?

【问题讨论】:

  • 添加一个关于您尝试做什么的示例有助于了解您需要什么。解释太啰嗦了。
  • @Dubas : 示例:我想向 PHP 文件 ( url = 192.168.1.123/myproject/uploads/treatphoto.php ) 发布一个 byte[] recorstore 记录和一个包含值“/MyDirectory”的字符串变量。
  • 你可以传入两个参数。一个是字节[],另一个是字符串名称。您可以在服务器端获取它。

标签: java php java-me httpconnection


【解决方案1】:

您可以使用 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'];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-19
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 2015-12-25
    • 2018-11-30
    • 1970-01-01
    相关资源
    最近更新 更多