REST API:如何使用Java在`JSON`中进行`POST`调用?

时间:2016-02-02 05:46:04

标签: java json web-services rest jersey

我是制作REST API的新手。我正在使用Jersy来制作API。以下是REST API的代码

import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

/**
 *
 * @author Yohan
 */
@Path("/json/metallica")
public class JsonService {

    @GET
    @Path("/getTrackInJSON")
    @Produces(MediaType.APPLICATION_JSON)
    public Track getTrackInJSON() {

        Track track = new Track();
        track.setTitle("Enter Sandman");
        track.setSinger("Metallica");

        return track;

    }

        @GET
    @Path("/getTrackArray")
    @Produces(MediaType.APPLICATION_JSON)
    public ArrayList<Track> getTrackArray() {

            ArrayList<Track> list = new ArrayList<Track>();

            for(int i=0;i<10;i++)
            {
                Track track = new Track();
        track.setTitle("Enter Sandman: "+i);
        track.setSinger("Metallica");

                list.add(track);
            }


        return list;

    }

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public void createTrackInJSON(Track track) {

        String result = "Track saved : " + track;
                System.out.println(result);


    }

}

现在,我尝试了GET命令,现在需要尝试POST命令。我在同一个项目的单独包中编写了以下代码。

import com.tutorialspoint.Track;
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.MediaType;
import javax.ws.rs.core.Response;


public class JerseyClientPost {

  public static void main(String[] args) {

    try {

        Client client = ClientBuilder.newClient();
                WebTarget target = client.target("http://localhost:8080/RESTFUL_API_SAMPLE/rest/json/metallica/").path("/post");

                Track track = new Track();
        track.setTitle("Enter Sandman: ");
        track.setSinger("Metallica");
                Track bean =
target.request(MediaType.APPLICATION_JSON_TYPE)
    .post(Entity.entity(track,MediaType.APPLICATION_FORM_URLENCODED_TYPE),
        Track.class);


      } catch (Exception e) {

        e.printStackTrace();

      }

    }
}

现在我收到以下错误。

Feb 02, 2016 11:11:02 AM org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor aroundWriteTo
SEVERE: MessageBodyWriter not found for media type=application/x-www-form-urlencoded, type=class com.tutorialspoint.Track, genericType=class com.tutorialspoint.Track.
org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/x-www-form-urlencoded, type=class com.tutorialspoint.Track, genericType=class com.tutorialspoint.Track.
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:247)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
    at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1130)
    at org.glassfish.jersey.client.ClientRequest.writeEntity(ClientRequest.java:502)
    at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:388)
    at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:285)
    at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:255)
    at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:700)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:696)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:448)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.post(JerseyInvocation.java:349)
    at JerseyClientPost.main(JerseyClientPost.java:38)
BUILD SUCCESSFUL (total time: 1 second)

这里发生了什么?

2 个答案:

答案 0 :(得分:1)

您错误地设置了POST媒体类型。应该是MediaType.APPLICATION_JSON_TYPE而不是MediaType.APPLICATION_FORM_URLENCODED_TYPE。因此,泽西岛抱怨它无法序列化您的Track对象。

我没有测试过这段代码,但您可以尝试这样的代码:

target.request().post(Entity.json(track));

答案 1 :(得分:1)

好的,让我们分解您的错误消息:

SEVERE: MessageBodyWriter not found for media type=application/x-www-form-urlencoded, 
  type=class com.tutorialspoint.Track, 
  genericType=class com.tutorialspoint.Track.

这看起来不错:

.post(Entity.entity(track,MediaType.APPLICATION_FORM_URLENCODED_TYPE), Track.class)

问:你的构建包中的com.tutorialspoint。*(包括Track.class)中的所有类文件是什么?在正确的子目录(com / tutorialspoint /)?

问:是&#34;追踪&#34; &#34; Form&#34;的子类你能否回复一个真实的表格&#34;对象

看看这篇文章:

jersey-client MessageBodyWriter not found for media type=application/x-www-form-urlencoded