我正在开发一个小型项目(REST 应用程序),其中我需要将 json 数据从 java 发布到 php 并显示它。但即使经过过去两天的尝试,我仍然无法完成这项任务。所以我制作了一个单独的文件来测试它是如何工作的。
以下是我在 netbeans 中运行的 .java 文件
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class NewClass {
public static void main(String[] args) {
String json = "{\"message\":\"This is a message\"}";
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost request = new HttpPost("http://localhost/test/somesite.php");
StringEntity params =new StringEntity("message=" + json);
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
// handle response here...
System.out.println(EntityUtils.toString(response.getEntity()));
EntityUtils.consume(response.getEntity());
} catch (Exception ex) {
ex.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
}
}
以下是我的 .php(somesite.php) 文件,位于 *C:\xampp\htdocs\test* 中。我使用xampp。
<?php
if(isset($_POST["message"]) && !empty($_POST["message"]))
{
print_r($_POST);
$json_string = $_POST["message"];
$json = json_decode($json_string);
print_r($json);
}
?>
当我在 netbeans 中运行 .java 文件时,我得到以下 output window
但是当我在浏览器中刷新我的 .php 页面时,我什么也没得到,我得到了 blank page 如何获取从 .java 发布到 .php 的 json 数据以在浏览器中显示?
感谢任何帮助,我是 json 和 php 的新手。谢谢。
最佳答案
这正在按预期工作。
当您在浏览器中访问 GET
请求的页面时,应该不会显示任何内容,因为您正在检查的 POST
为空/未设置。
同样,您的 java 请求作为 POST
请求发送到页面,并且您会在控制台中看到 PHP print_r
的输出,因此 =>
和 stdClass
。
要在浏览器中查看此内容,您需要从 PHP 到 Java 向服务发出请求。您当前正在尝试从 java 推送,然后在浏览器中查看它,这是不可能的。本质上你的代码是向后的。
PHP 有 curl
支持发出请求,或者您可以使用非常流行的 GuzzleHTTP 库。
关于java - 如何在网络浏览器中查看 post json 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41769491/