我需要帮助将json数据从Java类发布到php页面

时间:2019-01-14 16:29:10

标签: java php

显示其他网站发布的json数据时遇到麻烦。

我有一个Java类,该类具有发布请求并将json数据发布到我的php url。我对restful系统有点陌生。如果有新手问题,请原谅我。我目前在不同的端口上运行两个tomcat服务器。 这是我在Java类中的Java POST方法。

public static void POSTRequest(String responseces) throws IOException {

        final String POST_PARAMS = "{\n" + "\"userId\": 101,\r\n" +
        "    \"id\": 101,\r\n" +
        "    \"title\": \"Test Title\",\r\n" +
        "    \"body\": \"Test Body\"" + "\n}";
        System.out.println(POST_PARAMS);
        JSONObject json=new JSONObject();
        json.put("login", responseces);
        System.out.println(json);
        URL obj = new URL("http://localhost:8081/camundaretrive.php");
        HttpURLConnection postConnection = (HttpURLConnection)obj.openConnection();
        postConnection.setRequestMethod("POST");
        postConnection.setRequestProperty("Content-Type","application/json");
        postConnection.setDoOutput(true);
        OutputStream os = postConnection.getOutputStream();
        os.write(POST_PARAMS.getBytes());
        os.flush();
        os.close();
        int responseCode = postConnection.getResponseCode();
        System.out.println("POST Response Code :  " + responseCode);
        System.out.println("POST Response Message : " + postConnection.getResponseMessage());
        if (responseCode == HttpURLConnection.HTTP_CREATED) { //success
            BufferedReader in = new BufferedReader(new InputStreamReader(
                postConnection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in .readLine()) != null) {
                response.append(inputLine);
            } in .close();
            // print result
            System.out.println(response.toString());
        } else {
            System.out.println("POST NOT WORKED");
        }

这是我的php代码,可获取输入并以html形式回显。

<?php
$post = file_get_contents('php://input');
$result = json_decode($post);
echo $result;
?>

当我在邮递员中尝试这种方法时,效果很好。

The Response code :200
State State :OK

但是它无法创建数据。

0 个答案:

没有答案