java Rest API中的登录身份验证获取不支持的媒体类型

Posted

技术标签:

【中文标题】java Rest API中的登录身份验证获取不支持的媒体类型【英文标题】:login authentication in java Rest API getting Unsupported Media Type 【发布时间】:2018-12-07 08:32:31 【问题描述】:

在此示例中,我尝试获取 android 用户在登录时发送的参数来验证用户身份,作为响应,我提供了令牌,但在邮递员上检查时,我收到了 Unsupported Media Type Error

下面是 ApplicationConfig.java 类

package com.test;

import java.util.Set;
import javax.ws.rs.core.Application;

@javax.ws.rs.ApplicationPath("webresources")
public class ApplicationConfig extends Application 

@Override
public Set<Class<?>> getClasses() 
    Set<Class<?>> resources = new java.util.HashSet<>();
    addRestResourceClasses(resources);
    return resources;


/**
 * Do not modify addRestResourceClasses() method.
 * It is automatically populated with
 * all resources defined in the project.
 * If required, comment out calling this method in getClasses().
 */
private void addRestResourceClasses(Set<Class<?>> resources) 
     resources.add(com.test.AuthenticationEndpoint.class);



下面是 AuthenticationEndpoint.java 类

 package com.test;

 import java.security.SecureRandom;
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Statement;
 import javax.ws.rs.Consumes;
 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.MediaType;
 import javax.ws.rs.core.Response;

 @Path("/authentication")
 public class AuthenticationEndpoint 
 String token=null;
@POST
@Path("/getData")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response authenticateUser(@FormParam("username") String username, 
                                 @FormParam("password") String password) 

    try 

        // Authenticate the user using the credentials provided
        authenticate(username, password);

        // Issue a token for the user
       // String token = issueToken(username);

        // Return the token on the response
        return Response.ok(token).build();

     catch (Exception e) 
        return Response.status(Response.Status.FORBIDDEN).build();
          


private void authenticate(String username, String password) throws ClassNotFoundException, SQLException 
    // Authenticate against a database, LDAP, file or whatever
    // Throw an Exception if the credentials are invalid
     boolean status = false;
    credentials cred=new credentials();
    String user = cred.getUsername();
    String pass = cred.getPassword();       

    Connection conn = null;
    PreparedStatement pst = null;
    ResultSet rs = null;

  try 
  String sql="Select userid,password,area,designation from login";
  Class.forName("com.mysql.jdbc.Driver");
  Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename","root","");


  Statement st = con.createStatement();

        pst = conn
                .prepareStatement("select * from login where userid=? and password=?");
        pst.setString(1, user);
        pst.setString(2, pass);

        rs = pst.executeQuery();
        status = rs.next();

        if(status)
          token = issueToken(user);
    

     catch (Exception e) 
        System.out.println(e);
     finally 
        if (conn != null) 
            try 
                conn.close();
             catch (SQLException e) 
                e.printStackTrace();
            
        
        if (pst != null) 
            try 
                pst.close();
             catch (SQLException e) 
                e.printStackTrace();
            
        
        if (rs != null) 
            try 
                rs.close();
             catch (SQLException e) 
                e.printStackTrace();
            
        






private String issueToken(String username) 
    // Issue a token (can be a random String persisted to a database or a JWT token)
    // The issued token must be associated to a user
    // Return the issued token
   String user = username;
    SecureRandom random = new SecureRandom();
    byte bytes[] = new byte[20];
    random.nextBytes(bytes);
    String token = bytes.toString();


     Connection conn;
     Statement st;
     ResultSet rs=null;
     try 
     Class.forName("com.mysql.jdbc.Driver");

     conn=DriverManager.

     getConnection("jdbc:mysql://localhost:3306/basename","root","");

 st = conn.createStatement();
 String TableSQL = "UPDATE login SET token = ? WHERE userid = ?";
 PreparedStatement preparedStatement = conn.prepareStatement(TableSQL);
 preparedStatement.setString(1, token);
 preparedStatement.setString(2, user);
  // execute insert SQL stetement
 preparedStatement .executeUpdate();

catch(Exception e)


 return token;
   
   

在 credentials.java 类下

package com.test;

public class credentials 

private String username;
private String password;
private String area;
private String designation;

public String getUsername() 
    return username;


public void setUsername(String username) 
    this.username = username;


public String getPassword() 
    return password;


public void setPassword(String password) 
    this.password = password;

public String getArea() 
    return area;


public void setArea(String area) 
    this.area = area;


public String getDesignation() 
    return designation;


public void setDesignation(String designation) 
    this.designation = designation;



【问题讨论】:

@PathParam 建议这些变量是 URL 的一部分,您如何使用 Postman 调用您的服务? 对不起!我误加了PathParam,居然有FormParam 【参考方案1】:

@Consumes(MediaType.APPLICATION_FORM_URLENCODED)

由于您的端点正在使用 APPLICATION_FORM_URLENCODED,请确保在 Postman 中选择正确的媒体类型,如下所示

【讨论】:

以上是关于java Rest API中的登录身份验证获取不支持的媒体类型的主要内容,如果未能解决你的问题,请参考以下文章

如何在 java 中使用 REST API 身份验证? [关闭]

使用 otp 获取 api 令牌的 Django REST 框架的 JWT 身份验证

django rest 框架身份验证

登录时 WooCommerce REST API 身份验证失败

REST API 中基于令牌的身份验证

通过 REST API 传递“Windows 身份验证”?