我實現了基於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()
)。
上面的代碼,在那裏我檢查響應代碼,不工作...
你能幫幫我嗎?
定義 「不工作」 精確。你期望發生什麼,魔杖會發生什麼呢? –