JAX-RS @PathParam How to pass a String with slashes, hyphens & equals too

后端 未结 5 1704
北荒
北荒 2020-12-14 14:36

I am new to JAX-RS and I am trying to use Jersey to build a simple RESTful Webservice.

I have 2 questions. Please clarify these:

  1. I am trying to have

相关标签:
5条回答
  • 2020-12-14 15:05

    This is how you enable slashes in path params:

    @Path("{inchiname : .+}")
    public String get3DCoordinates(@PathParam("inchiname")String inchiName) 
    
    0 讨论(0)
  • 2020-12-14 15:06

    The parameters should be URL encoded. You can use java.net.URLEncoder for this.

    String encodedParam = URLEncoder.encode(unencodedParam, "UTF-8");
    

    The / will then be translated to %2F.

    0 讨论(0)
  • 2020-12-14 15:13

    Tomcat does not Accept %2F in URLs: http://tomcat.apache.org/security-6.html. You can turn off this behavior.

    0 讨论(0)
  • 2020-12-14 15:15

    The following should work:

    @GET
    @Path("{inchiname : (.+)?}")
    @Produces("application/xml")
    public String get3DCoordinates(@PathParam("inchiname")String inchiName) {
    

    (This is sort of mentioned in another answer and comment, I'm just explicitly putting it in a separate answer to make it clear)

    0 讨论(0)
  • 2020-12-14 15:19

    I got this to work using @QueryParam() rather than @PathParam.

    @Path("/inchi")
    public class InChIto3D {
        @GET
        //@Path("{inchiname}")
        @Produces("application/xml")
        public String get3DCoordinates(@QueryParam("inchiname") String inchiName) {
              String ne="";
              try{
                  URL eutilsurl = new URL(
                          "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?"
                          + "db=pccompound&term=%22"+inchiName+"%22[inchi]");
                  BufferedReader in = new BufferedReader(
                                    new InputStreamReader(eutilsurl.openStream()));
                 String inputline;
                 while ((inputline=in.readLine())!=null)
                     ne=ne+inputline;
              }catch (MalformedURLException e1) {
              }catch (IOException e2){
              }
              return ne;
        }
    }
    

    Thus the URL structure would be like this http://myrestservice.com/rest/inchi?inchiname=InChIhere

    With @PathParam I read in the API that it will not accept slashes. I am wondering if I can use any Regular Expression in @Path just to ignore all slashes in the string that would be entered in quotes" ".

    0 讨论(0)
提交回复
热议问题