我有一个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从客户端传递到服务器?
我跟着mkyong的http://www.mkyong.com/webservices/jax-rs/restful-java-client-with-jersey-client/教程(对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数据传递给我的服务器。任何人都可以为此提供客户端和服务器代码吗?
提前谢谢
答案 0 :(得分:0)
将@Consumes添加为“ application / json”,并在JsonObject Type中指定方法参数。您必须添加了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");
//................
//........
//.....
}