我实现了基于Jersey的REST风格的Web服务。 当发送我的请求时,我首先检查是否定义了一些必需的参数,如果没有,我将返回带有错误代码和错误消息的响应。 下面是摘录:无法从http请求中获取JSON
@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());
}
...
}
我的问题是,我得到的responseCode
,但我不知道怎么弄的错误消息,应该在响应中的某个地方,对吗? (Response.status(Status.BAD_REQUEST).entity(**errorMessages**).build()
)。
上面的代码,在那里我检查响应代码,不工作...
你能帮帮我吗?
定义 “不工作” 精确。你期望发生什么,魔杖会发生什么呢? –