Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Can';无法从http请求获取JSON_Java_Json_Web Services_Jersey 2.0 - Fatal编程技术网

Java Can';无法从http请求获取JSON

Java Can';无法从http请求获取JSON,java,json,web-services,jersey-2.0,Java,Json,Web Services,Jersey 2.0,我实现了一个基于Jersey的RESTful web服务。 在发送请求时,我首先检查是否定义了一些强制参数,如果没有,我将返回一个带有错误代码和错误消息的响应。 以下是片段: @Path( "/groups" ) @RequestScoped @Consumes( MediaType.APPLICATION_JSON ) @Produces( value = {MediaType.APPLICATION_JSON, MediaType.TEXT_XML} ) public class Group

我实现了一个基于Jersey的RESTful web服务。 在发送请求时,我首先检查是否定义了一些强制参数,如果没有,我将返回一个带有错误代码和错误消息的响应。 以下是片段:

@Path( "/groups" )
@RequestScoped
@Consumes( MediaType.APPLICATION_JSON )
@Produces( value = {MediaType.APPLICATION_JSON, MediaType.TEXT_XML} )
public class GroupResource
{
  ...
  @POST
  public Response createGroup( Group group, @Context UriInfo uriInfo )
  {
    logger.info("-------------------");
    logger.info("Create group");
    logger.fine(group.toString());
    logger.info("-------------------");

    // check mandatory fields
    if (!checkMandatoryFields(group, errorMessages))
    {
      return Response.status(Status.BAD_REQUEST).entity(errorMessages).build();
    }
  ...
}
然后我实现了一个JUnit测试来测试它:

@Test
  public void testCreateGroup()
  {
    try
    {
      URL url = new URL(URL_GROUPS_WS);

      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setDoOutput(true);
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Content-Type", "application/json");

      String json2send = "{\"grid\":\"1\", \"gidNumber\":\"2\", \"groupName\":\"TestGroup\", \"groupDescription\":\"Initial description\", \"targetSystems\":[\"ADD TS1\"]}";

      OutputStream os = conn.getOutputStream();
      os.write(json2send.getBytes());
      os.flush();

      System.out.println("XXXXXXXX Sending request XXXXXXXX \n");

      if (conn.getResponseCode() != 200)
      {
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        StringBuffer error = new StringBuffer();
        String inputLine;
        while ((inputLine = in.readLine()) != null)
        {
          error.append(inputLine);
        }

        in.close();

        throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode() + error.toString());
      }
  ...
}
我的问题是我得到了
响应code
,但我不知道如何得到错误消息,它应该在响应的某个地方,对吗?(
Response.status(status.BAD_REQUEST).entity(**errorMessages**).build()

上面的代码,我检查的响应代码,不工作


您能帮我一下吗?

用ErrorStream代替InputStream-

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));

ErrorStream将在出现错误时为您提供响应。

这不是正确测试jersey组件的方法,事实上,您应该依靠测试来测试组件,因为它隐藏了很多复杂性,因此您的单元测试很容易阅读和维护

您当前的代码太容易出错,应该避免使用

假设您使用的是
maven
,则需要在
test
范围内将接下来的2个依赖项添加到项目中

<dependency>
    <groupId>org.glassfish.jersey.test-framework</groupId>
    <artifactId>jersey-test-framework-core</artifactId>
    <version>2.24</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.test-framework.providers</groupId>
    <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
    <version>2.24</version>
    <scope>test</scope>
</dependency>
准确定义“不起作用”。你预计会发生什么,魔杖会发生什么?
public class GroupResourceTest extends JerseyTest {

    @Override
    protected Application configure() {
        return new ResourceConfig(GroupResource.class);
    }

    @Test
    public void testCreateGroup() {
        Group group = // create your group instance to test here
        Response response = target("/groups")
            .request()
            .accept(MediaType.APPLICATION_JSON)
            .post(Entity.entity(group, MediaType.APPLICATION_JSON));
        Assert.assertEquals(Response.Status.BAD_REQUEST, response.getStatus());
        Assert.assertEquals("My error message", response.readEntity(String.class));
    }
}