java - 如何将命名变量发布到 PHP 文件?

标签 java php java-me httpconnection

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

最佳答案

您可以使用 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[] 数组,您需要将字节数组转换为以某种可打印编码(如 base64)编码的字符串

GET 方法还对可以安全传递的数据有排序限制(通常为 2048 字节)

另一种方法“POST”更复杂(但不是很多),是添加更多数据的方法。

您需要准备 HttpConnection 以将数据作为 POST 传递。 另外,urlParamenters 中存储的数据需要根据 url 编码。 使用 post 传递数据与 GET 类似,但不是在 url 旁边添加所有变量,而是将变量添加到 httpConnection 请求的流中。

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'];

关于java - 如何将命名变量发布到 PHP 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7088833/

相关文章:

php - 复杂的 Laravel 关系

php - $this->query() 中条件为空的 Codeigniter

java - j2me 网络、线程和死锁

synchronization - 在本地同步来自 JavaME mobile 的数据

iphone - 如何加强 Java ME 生态系统

java - Websphere httpclient NoSuchMethodError org.apache.http.conn.Scheme

java - 如何使用 mysql 解决 Spring Boot 应用程序上的 "Communications link failure"问题?

java - 需要存储另一个领域模型的领域模型

Java列表设置方法

php - WordPress 表前缀不能为空