java—如何从客户机通过post方法使用json对象

mtb9vblg  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(271)

我有一个json对象,我需要通过post将它传递到我的服务器。json在我的客户机中是硬编码的。下面是我的服务器程序(test.java)-请注意这是为了学习。所以解释清楚。。。

@Path("/json/product")
    public class Test {

        @POST
        @Path("/post")

        @Consumes(MediaType.APPLICATION_JSON)
        public Response createProductInJSON() {

            return Response.status(201).entity(....).build();

        }
      }

json是如何从客户机传递到服务器的?
我跟着http://www.mkyong.com/webservices/jax-rs/restful-java-client-with-jersey-client/ mkyong的教程(对post方法感到困惑)。从客户端程序中,需要通过post方法传递和接收硬编码的json格式…在服务器上。json能否作为参数从客户机传递到服务器。。。?或者怎么做。。。。下面是我的示例客户端程序。。。。

public static void main(String[] args) {

          try {

            URL url = new URL("http://localhost:8080/Snapshothealthapp1/rest/json/product/post");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            String JSON_DATA =
                     "{" 
                       + "  \"SnapshotRequest\": [" 
                       + "    {" 
                       + "      \"AuthenticationType\": \"email\"," 
                       + "      \"EmailAddress\": \"test@gmail.com\","                  
                       + "      \"Password\" : \"12345\"," 
                       + "      \"PracticeID\" : \"null\"," 
                       + "      \"DeviceID\" : \"null\""
                       + "    } +   ]"
                   + "}";
//          request.body("application/json", JSON_DATA);
//          String input = "{\"singer\":\"Metallica\",\"title\":\"Fade To Black\"}";

            OutputStream os = conn.getOutputStream();
            os.write(JSON_DATA.getBytes());
            os.flush();
            if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
                throw new RuntimeException("Failed : HTTP error code : "
                    + conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }

            conn.disconnect();

          } catch (MalformedURLException e) {

            e.printStackTrace();

          } catch (IOException e) {

            e.printStackTrace();

         }

我需要将字符串json数据传递给我的服务器。有人能给我一个客户端和服务器代码吗?
提前谢谢

i7uaboj4

i7uaboj41#

将@consumes添加为“application/json”,并在jsonobject类型中指定方法参数。您必须添加javax.json.jar(通常随jax-rs提供)。

@Path("/create")
@POST
@Consumes (MediaType.APPLICATION_JSON) //Specify the POST MediaType as "application/json"
@Produces(MediaType.APPLICATION_JSON)
public Book createBook(JsonObject postData //Consumable JSON Object param  ) {

     System.out.println( postData); //This prints the client's JSON object from the Request Body

     //Do your work here with the postData ..........
     String value1 = postData.getString("key1");
     int value2 = postData.getInt("key2");
     //................
     //........
     //.....
}

相关问题