[英]Java HTTP POST request (JSON) to PHP server
我有一个需要将json发送到php web服务的应用程序(Java)。
这是我以JSON发送User的方法:
public void login(User user) throws IOException {
Gson gson = new Gson();
String json = gson.toJson(user);
System.out.println(json);
String url = "http://localhost/testserveur/index.php";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection)obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("json", json);
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.flush();
}
int responseCode = con.getResponseCode();
System.out.println(responseCode);
}
和我的PHP代码:
$string=$_POST['json'];
我试图在数据库中插入,但是$_POST['json']
不存在。
我没看到您发布任何内容。 将此添加到您的代码:
String param = "json=" + URLEncoder.encode(json, "UTF-8");
wr.write(param.getBytes());
这是不对的:
con.setRequestProperty("json", json);
setRequestProperty不用于设置HTTP有效负载。 它用于设置HTTP标头。 例如,无论如何,您应该相应地设置内容类型。 像这样:
con.setContentType("application/json");
您要发布的实际数据将进入HTTP正文。 您只需将其写入流的末尾(刷新之前):
这里是否需要转义数据取决于您在Web服务器上的实现。 如果您阅读文章的正文并将其立即解释为JSON,则无需转义:
wr.write(json);
如果您通过参数传输一个或多个JSON字符串(看起来像,因为您像$ _POST ['json']一样在服务器上对其进行了解析),则需要对字符串进行url转义:
wr.write("json=" + URLEncoder.encode(json, "UTF-8"));
我不是很熟悉php。 在进一步处理接收到的json-string之前,您可能需要在服务器上对该字符串进行url解码。
谢谢您的帮助。
这有效:
公共无效登录(用户)抛出IOException {
Gson gson = new Gson(); String json = gson.toJson(user); System.out.println(json); String url = "http://localhost/testserveur/index.php"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setDoOutput(true); con.setRequestMethod("POST"); con.setRequestProperty("json", json); OutputStream os = con.getOutputStream(); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); //wr.write(new String("json=" + json).getBytes()); String param = "json=" + URLEncoder.encode(json, "UTF-8"); wr.write(param.getBytes()); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println(responseCode); }
PHP的:
$ string = $ _ POST ['json'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.