用球衣在 POST 中检索 JsonObject
我的应用程序有一些问题,我发送了一个 POST 请求,但我无法在我的服务器中检索 JsonObject,这是要发送的代码:
I have some problems in my application, I send a POST request, but I cannot retrieve the JsonObject in my server, this is the code to send:
String quo = "{"network": {"label": "new net 111","cidr": "10.20.105.0/24"}}";
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
JsonParser json = new JsonParser();
JsonObject jo = (JsonObject)json.parse(quo);
ClientConfig config = new ClientConfig();
Client client = ClientBuilder.newClient(config);
WebTarget target = client.target("http://localhost:7999/jersey/rest/network/"+tenant_id);
Response oj = target.request().accept(MediaType.APPLICATION_JSON)
.header("X-Auth-Token", token)
.post(Entity.json(gson.toJson(jo)));
尝试检索:
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("/{tenant_id}")
public String createNetwork(@HeaderParam(value = "X-Auth-Token") String authToken,
@PathParam(value = "tenant_id") String tenant_id,
JsonObject network){
Response response = client.target(NOVA_ENDPOINT+tenant_id)
.request(MediaType.APPLICATION_JSON)
.header("X-Auth-Token", authToken)
.post(Entity.json(gson.toJson(network)));
System.out.println("Hello");
String responseJson = response.readEntity(String.class);
JsonObject 网络似乎是空的,实际上它没有执行方法(Hello is not print"),我得到的错误是Invalid request body"(因为我认为JsonObject 是空的)..我的代码有什么问题?
JsonObject network seems to be empty, in fact it doesn't execute the method ("Hello is not printed"), the error I get is "Invalid request body" (because the JsonObject is empty I think).. What's wrong with my code?
好的,我知道问题与 Json 处理有关,例如我正在使用 Gson.这是我根据用户建议改进的代码(简化版),但我仍然有问题..
Ok, I understood that the problem is related to Json handling such as I'm using Gson. This is my improved code (simplified version) following users suggestion, but I still have problems..
客户端:
package openstack;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.net.URI;
public class Post {
public static HttpServer startServer() {
final ResourceConfig resourceConfig = new ResourceConfig()
.packages("openstack")
.register(GsonMessageBodyHandler.class);
return GrizzlyHttpServerFactory.createHttpServer(URI.create("http://localhost:7999/jersey/rest"), resourceConfig);
}
public static void main(String[] args) {
String quo = "{"keypair": {"name": "MyKey"}}";
HttpServer server = startServer();
Client client = ClientBuilder.newClient();
client.register(GsonMessageBodyHandler.class);
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
JsonParser json = new JsonParser();
JsonObject jo = (JsonObject)json.parse(quo);
WebTarget target = client.target("http://localhost:7999/jersey/rest/test/prova");
System.out.println(jo);
Response oj = target.request().post(Entity.json(jo));
String responseString = oj.readEntity(String.class);
System.out.println(responseString);
}
}
服务器端:
package openstack;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
@Path("/test")
public class Test {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
Parliament parliament = new Parliament();
JsonParser json = new JsonParser();
private final Client client;
public Test() {
client = ClientBuilder.newClient().register(GsonMessageBodyHandler.class);
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/prova")
public Response mymethod(JsonObject keypairsob){
return Response.ok(keypairsob).build();
}
}
我在我的包中创建了一个 GsonMessageBodyHandler.java,其中包含用户 peeskillet 建议的以下代码.将 jersey-container-grizzly2-http.jar 添加到我的 web-inf/lib 中(我不知道如何正确使用 Maven),但仍然无法正常工作..我错过了什么?
I created a GsonMessageBodyHandler.java in my package with the code suggested below by the user peeskillet. Added jersey-container-grizzly2-http.jar to my web-inf/lib (I don't know how to proper use Maven), but still doesn't work.. what am I missing?
推荐答案
有一种简单的方法可以使用 post 请求获取 com.google.gson.JsonObject 类型的 JsonObject.
There's a simple way to get the JsonObject in com.google.gson.JsonObject type using a post request.
我假设 com.google.gson 、 jersey 和 jax-rs 的所有依赖项都已添加.
I am assuming that all the dependencies for com.google.gson , jersey and jax-rs are already added.
在服务器端,您需要有类似于以下的代码:
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
@Path("/api")
public class JersyAPI {
private JsonParser parser= new JsonParser();
@POST
@Path("/pudding")
@Consumes("application/json")
public Response postTest(String requestBody){
Response re = Response.status(200).build();
try{
JsonObject inputObjectJson = parser.parse(requestBody).getAsJsonObject();
上面的代码有一个使用路径/api/pudding 定义的休息端点,它接受请求正文作为字符串.在服务器端收到 Json 作为字符串后,可以使用 com.google.gson.JsonParser 将其直接转换为 com.google.gson.JsonObject 并在您的程序中使用.
The code above has a rest endpoint defined with path /api/pudding and it is accepting the Request Body as String. Once you receive the Json as string on server side, com.google.gson.JsonParser can be used to convert it into the com.google.gson.JsonObject directly and this can be used in your program.
要在服务器端发出请求,您发布的请求应如下所示:
POST /rest/api/pudding HTTP/1.1
Host: localhost:8082
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: c2b087d9-4830-c8a8-2a19-78273a73898c
{
"id": 1312312,
"name": "Test",
"data": {
"test" : "data"
},
}
相关文章