unexpected 's' in response of restful service
Asked Answered
M

5

2

i am trying to learn restful services and as part of that i am designing a sample request and response page...see i am getting everything right except the following resource called:

<i>

package com.tutorialspoint;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/RestService")
public class CrunchifyRESTService {
    @POST
    @Path("/crunchifyService")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response crunchifyREST(InputStream incomingData) {
        StringBuilder crunchifyBuilder = new StringBuilder();
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
            String line = null;
            while ((line = in.readLine()) != null) {
                crunchifyBuilder.append(line);
            }
        } catch (Exception e) {
            System.out.println("Error Parsing: - ");
        }
        System.out.println("Data Received: " + crunchifyBuilder.toString());

        // return HTTP response 200 in case of success
        return Response.status(200).entity(crunchifyBuilder.toString()).build();
    }

    @GET
    @Path("/verify")
    @Produces(MediaType.APPLICATION_JSON)
    public Response verifyRESTService(InputStream incomingData) {
        String result = "CrunchifyRESTService Successfully started..";

        // return HTTP response 200 in case of success
        return Response.status(200).entity(result).build();
    }

    @POST
    @Path("/login")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response loginserv(newUser user){
        String data="";
            data=user.uname+" and auth "+user.pwd;


        return Response.status(200).entity(data).build();
    }

}

and the request i am using is POST and the url is http://localhost:8080/com/rest/RestService/login/sudheer/123

and the response i am getting is

<!DOCTYPE html>
<html>
    <head>
        <title>Apache Tomcat/8.5.4 - Error report</title>
        <style type="text/css">H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}.line {height: 1px; background-color: #525D76; border: none;}</style>
    </head>
    <body>
        <h1>HTTP Status 415 - Unsupported Media Type</h1>
        <div class="line"></div>
        <p>
            <b>type</b> Status report
        </p>
        <p>
            <b>message</b>
            <u>Unsupported Media Type</u>
        </p>
        <p>
            <b>description</b>
            <u>The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.</u>
        </p>
        <hr class="line">
        <h3>Apache Tomcat/8.5.4</h3>
    </body>
</html>

Response headers

Content-Language →en
Content-Length →1133
Content-Type →text/html;charset=utf-8
Date →Mon, 24 Oct 2016 06:35:48 GM

T

and know what is the exact problem with the code pls clarify me

Martensite answered 24/10, 2016 at 6:0 Comment(6)
how do you run the application?Parisparish
I have Tomcat running....created a war and deployed into webapp folder..and for frontend simulation i am using POSTMANMartensite
seems your url is something wrong if you application name is RestService it can not start as /com/restParisparish
see "com" is project name, "rest " is comman path i have given in web.xml, find the full source updated u will get a clear pictureMartensite
Can you add your complete response in the question?Metallist
ok adding the response after taking consideration changes from @AmitaMartensite
L
1

Unsupported media type error usually means that the Content-type header of the request is not as server expects. In your case, the line

@Consumes(MediaType.APPLICATION_JSON)

signals that your REST API expects JSON request. You haven't posted the exact request made with Postman, but if you add in Headers section new entry with key Content-Type and value application/json the error should disappear. Of course, make sure that your request really is in correct JSON format - use e.g. http://jsonlint.com to validate the request. Body of the request should be something along the lines:

{
    uname : "sudheer",
    pwd : "123"
}
Leucocratic answered 24/10, 2016 at 6:48 Comment(3)
sorry i am following all the conventions you have specifiedMartensite
@Martensite I don't understand, you created a POST request with the specified body, added header I mentioned and the error is still there?Leucocratic
yes..i too wonder as i am just new to webservices....see these are the jars right now configured in project pom....javax.servlet-api,jersey-server,jackson-core,jackson-databind,json....i don't understand what exactly i am missing...Martensite
M
1

Add the following dependencies in your pom.xml

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson-version}</version> // 2.4.3
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version> // 2.4.3
</dependency>

Then define your controller as :-

@POST
@Path("/login")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response loginserv(@RequestBody newUser user){ 
//I really hope you have newUser as your classname better follow Java conventions and rename it as NewUser
    String data="";
        data=user.uname+" and auth "+user.pwd;


    return Response.status(200).entity(data).build();
}

To use @RequestBody you better use <mvc:annotation-driven />

This answer is somewhat copy of this. So please upvote there if it works. :)

Metallist answered 24/10, 2016 at 6:49 Comment(3)
hi first of all thanks for your pinpoint observation...and second i am just using a plain maven web project archtype..that's it i am not using any mvc framework which will eventually makes the footprint quite a bit large..and i heard we don't need to use any MVC framework just for request and response kind of communications thats just in json..:SMartensite
@Sud: Thanks, got your sarcasm :|Metallist
@DaveRanjan nothin personal dude..anyway thanks for your help...:)Martensite
S
0

For POST request, you do not send data by specifying it in the path. Instead, create a wrapper class like this:

class User{
    private String uname;
    private String pwd;

   // getter and setter methods
}

and then write the service as:

@Path("/login")
public class LoginService {
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response loginserv(User user){
            String data="";

            data=user.uname+" and auth "+user.pwd;

            return Response.status(200).entity(data).build();
    }
}

I guess, the unexpected 's' is displayed because the service does not expect the path you are passing as URL.

Sandblast answered 24/10, 2016 at 6:21 Comment(2)
I have handled RESTful web services using AJAX. Check them out at : github.com/amita-shukla/mail-aggregator/blob/master/src/…, and github.com/amita-shukla/mail-aggregator/blob/master/WebContent/… [check invokeLogin() method ] Hope it will help you.Sandblast
Firstly, you can try removing @Consumes(MediaType.APPLICATION_JSON)Sandblast
H
0

In your case, I notice 2 errors: 1) Your error description clearly says that, "The server refused this request because the request entity is in a format not supported by the requested resource for the requested method"

The content-type you are consuming in your request is @Consumes(MediaType.APPLICATION_JSON), So in request you have to provide your POST data in JSON format like {"key1":"value1","key2":"value2"}.

2) You received response "unexpected 's'" because you are producing response content-type @Produces(MediaType.APPLICATION_JSON) i.e. in JSON format & at the time of sending response you are creating String by using (.toString() method)

So use @Produces (MediaType.ALL_VALUE) to get JSON as well as string in response.

Hackler answered 21/9, 2017 at 7:43 Comment(0)
H
0

Open "Raw" tab (mode) in Postman to see exact text response. The message itself just tells "Postman can't convert received text into [whatever format you've selected] because of unexpected character".

Heroics answered 21/3, 2018 at 14:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.