2013-07-22 21 views
0

我有一個Jersey Web服務,我需要解析與請求一起發送的一些json數據。已爲此請求調用java.lang.IllegalStateException:getInputStream()

@POST 
@Path ("/authenticate") 
@Produces (MediaType.APPLICATION_JSON) 
public Response authenticate (@Context HttpServletRequest request) 
{ 

    try { 
     StringBuffer json = new StringBuffer(); 
     BufferedReader reader = request.getReader(); 
     int line; 
     while ((line = reader.readLine()) != null) 
     { 
      json.append(line); 
     } 
      System.out.prinln (json); 
    } catch (IOException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 

    return Response.ok().entity(json).build(); 
}//end authenticate method 

該服務產生以下異常:

java.lang.IllegalStateException: getInputStream() has already been called for this request

我做了一些研究。這表明一個getReadergetInputStream不能在同一請求調用。因此,它似乎已經調用了一個getInputStream實例。如果我沒有明確地打電話,這怎麼可能?爲了解決這個問題,我使用了getInputStream方法,而不是

try { 
     ServletInputStream reader = request.getInputStream(); 
     int line; 
     while ((line = reader.read()) != -1) 
     { 

     } 

    } catch (IOException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 

    return Response.ok().entity().build(); 

用這種方法,我該如何使用字節的INT獲得JSON?

+0

爲什麼你不讓球衣生成JSON你的目標? –

回答

4

好像你錯過了@Consumes註釋。你意識到你可以擁有一種方法;

@POST 
@Path ("/authenticate") 
@Consumes (MediaType.APPLICATION_JSON) 
@Produces (MediaType.APPLICATION_JSON) 
public Response authenticate (String entity) { 

    //entity contains the posted content 

} 

無需自己讀取流?如果你有一個代表你消費的JSON的bean,那麼你可以將它作爲一個方法參數添加,澤西會自動爲你解析;

@POST 
@Path ("/authenticate") 
@Consumes (MediaType.APPLICATION_JSON) 
@Produces (MediaType.APPLICATION_JSON) 
public Response authenticate (AuthBean auth) { 

    //auth bean contains the parsed JSON 

} 


class AuthBean { 

    private String username; 
    private String password; 

    // getters/setters 

} 

示例後;

{ 
"username" : "[email protected]", 
"password" : "super s3cret" 
} 
相關問題