【问题标题】:unexpected 's' in response of restful service出乎意料的's'响应宁静的服务
【发布时间】:2017-03-05 19:52:33
【问题描述】:

我正在尝试学习宁静的服务,作为其中的一部分,我正在设计一个示例请求和响应页面...请参阅我得到的一切都正确,除了以下内容 资源调用:

<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();
    }

}

我使用的请求是 POST,url 是 http://localhost:8080/com/rest/RestService/login/sudheer/123

我得到的回应是

<!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>

响应头

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

T

并知道代码的确切问题是什么,请澄清一下

【问题讨论】:

  • 如何运行应用程序?
  • 我正在运行 Tomcat....创建了一个战争并部署到 webapp 文件夹中..对于前端模拟,我正在使用 POSTMAN
  • 如果您的应用程序名称是 RestService,您的 url 似乎有问题,它不能以 /com/rest 开始
  • 看到“com”是项目名称,“rest”是我在web.xml中给出的comman路径,找到完整的源更新你会得到一个清晰的图片
  • 您能在问题中添加完整的回答吗?

标签: java restful-url


【解决方案1】:

不支持的媒体类型错误通常意味着请求的Content-type 标头与服务器期望的不符。在您的情况下,该行

@Consumes(MediaType.APPLICATION_JSON)

表示您的 REST API 需要 JSON 请求。您尚未发布使用 Postman 提出的确切请求,但如果您在 Headers 部分中添加带有键 Content-Type 和值 application/json 的新条目,则错误应该会消失。当然,请确保您的请求确实是正确的 JSON 格式 - 使用例如http://jsonlint.com 验证请求。请求的正文应该是这样的:

{
    uname : "sudheer",
    pwd : "123"
}

【讨论】:

  • 对不起,我遵循您指定的所有约定
  • @Sud 我不明白,你用指定的body创建了一个POST请求,添加了我提到的header,错误仍然存​​在?
  • 是的..我也很奇怪,因为我只是 webservices 的新手....看到这些是现在在项目 pom 中配置的 jars....javax.servlet-api,jersey-server, jackson-core,jackson-databind,json....我不明白我到底错过了什么...
【解决方案2】:

在您的 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>

然后将您的控制器定义为:-

@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();
}

要使用@RequestBody,最好使用&lt;mvc:annotation-driven /&gt;

这个答案有点复制this。因此,如果它有效,请在那里投票。 :)

【讨论】:

  • 嗨,首先感谢您的精确观察...其次,我只是使用普通的 maven web 项目 archtype..就是这样,我没有使用任何 mvc 框架,这最终会使足迹相当有点大..我听说我们不需要使用任何 MVC 框架来处理请求和响应类型的通信,这只是在 json 中..:S
  • @Sud:谢谢,得到你的讽刺:|
  • @DaveRanjan nothin 个人花花公子..无论如何感谢您的帮助...:)
【解决方案3】:

对于 POST 请求,您不会通过在路径中指定数据来发送数据。 相反,创建一个像这样的包装类:

class User{
    private String uname;
    private String pwd;

   // getter and setter methods
}

然后将服务写成:

@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();
    }
}

我猜,显示意外的“s”是因为服务不希望您作为 URL 传递的路径。

【讨论】:

【解决方案4】:

在您的情况下,我注意到 2 个错误: 1)您的错误描述清楚地表明, "服务器拒绝了这个请求,因为请求实体的格式不受所请求方法的请求资源支持"

您在请求中使用的内容类型是@Consumes(MediaType.APPLICATION_JSON),因此在请求中您必须提供 JSON 格式的 POST 数据,例如 {"key1":"value1","key2 ":"value2"}。

2) 您收到响应“unexpected 's'”,因为您正在生成响应内容类型 @Produces(MediaType.APPLICATION_JSON) 即 JSON 格式,并且在发送响应时您正在使用 (.toString( ) 方法)

所以使用 @Produces (MediaType.ALL_VALUE) 来获取 JSON 以及字符串作为响应。

【讨论】:

    【解决方案5】:

    在 Postman 中打开“原始”选项卡(模式)以查看准确的文本响应。消息本身只是告诉“邮递员无法将收到的文本转换为 [由于意外字符而选择的任何格式]”。

    【讨论】:

      猜你喜欢
      • 2016-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 2014-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多