Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何编写控制器类以允许内容类型:application/json和application/x-www-form-urlencoded_Java_Json_Spring_Rest - Fatal编程技术网

Java 如何编写控制器类以允许内容类型:application/json和application/x-www-form-urlencoded

Java 如何编写控制器类以允许内容类型:application/json和application/x-www-form-urlencoded,java,json,spring,rest,Java,Json,Spring,Rest,我将请求作为内容类型发送给我的控制器类请求:application/json和application/x-www-form-urlencoded格式,它应该允许这两种类型 但是当我使用请求类型作为应用程序/x-www-form-urlencoded时,它正在工作,但当我使用请求应用程序/json时,该代码不工作,它给出400响应状态。如何解决此问题。您可以在@RequestMapping中定义consumes属性,并在xml中定义ViewResolver。 下: @RequestMappingc

我将请求作为内容类型发送给我的控制器类请求:application/json和application/x-www-form-urlencoded格式,它应该允许这两种类型


但是当我使用请求类型作为应用程序/x-www-form-urlencoded时,它正在工作,但当我使用请求应用程序/json时,该代码不工作,它给出400响应状态。如何解决此问题。

您可以在@RequestMapping中定义consumes属性,并在xml中定义ViewResolver。 下:

@RequestMappingconsumes=[] 内容协商解决方案
您可以在@RequestMapping中定义consumes属性,在xml中定义ViewResolver。 下:

@RequestMappingconsumes=[] 内容协商解决方案
您需要为请求的内容类型标头使用consumes注释元素,并为请求的Accept标头生成注释元素:

@RequestMapping(value = "/home",
               method = RequestMethod.POST,
             consumes = {"application/json", "application/x-www-form-urlencoded"},
             produces = "application/json")
参考:

这些RequestMapping元素可用于Spring4。如果使用Spring 2,则需要使用params元素,而不是consumes&Products元素:

@RequestMapping(value = "/home",
               method = RequestMethod.POST,
               params = {"content-type=application/json",
                         "content-type=application/x-www-form-urlencoded",
                         "Accept=application/json"})

检查类似问题:

您需要为请求的内容类型标头使用consumes注释元素,并为请求的Accept标头生成注释元素:

@RequestMapping(value = "/home",
               method = RequestMethod.POST,
             consumes = {"application/json", "application/x-www-form-urlencoded"},
             produces = "application/json")
参考:

这些RequestMapping元素可用于Spring4。如果使用Spring 2,则需要使用params元素,而不是consumes&Products元素:

@RequestMapping(value = "/home",
               method = RequestMethod.POST,
               params = {"content-type=application/json",
                         "content-type=application/x-www-form-urlencoded",
                         "Accept=application/json"})
检查类似问题:

使用Oauth2令牌

:  public void login()
    {
        string userName = "abc@mailinator.com";
        string password = "Pass@123";
        //var registerResult = Register(userName, password);

        //Console.WriteLine("Registration Status Code: {0}", registerResult);

        string token = GetToken(userName, password);
        Console.WriteLine("");
        Console.WriteLine("Access Token:");
        Console.WriteLine(token);


        Dictionary<string, string> tokenDic = GetTokenDictionary(token);

        GetUserInfo(tokenDic["access_token"]);

    }


    private const string baseUrl = "http://localhost/WebApplication4";
    static string GetToken(string userName, string password)
    {
        var pairs = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>( "grant_type", "password" ), 
            new KeyValuePair<string, string>( "userName", userName ), 
            new KeyValuePair<string, string> ( "password", password )
        };

        var content = new FormUrlEncodedContent(pairs);
        using (var client = new HttpClient())
        {
            var response = client.PostAsync(baseUrl + "/Token", content).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }


    static Dictionary<string, string> GetTokenDictionary(string token)
    {
        // Deserialize the JSON into a Dictionary<string, string>
        Dictionary<string, string> tokenDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(token);
        return tokenDictionary;
    }

    static HttpClient CreateClient(string accessToken = "")
    {
        var client = new HttpClient();
        if (!string.IsNullOrWhiteSpace(accessToken))
        {
            client.DefaultRequestHeaders.Authorization =
                new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
        }
        return client;
    }

    static string GetUserInfo(string token)
    {
        using (var client = CreateClient(token))
        {
            var response = client.GetAsync(baseUrl + "/api/Account/UserInfo").Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }
  <form id="form1" action="@ViewBag.Action" method="POST">
    <div>
        Access Token<br />
        <input id="AccessToken" name="AccessToken" width="604" type="text" value="@ViewBag.AccessToken" />
        <input id="Authorize" name="submit.Authorize" value="Authorize" type="submit" />
        <br />
        <br />
        Refresh Tokensh Token<br />
        <input id="RefreshToken" name="RefreshToken" width="604" type="text" value="@ViewBag.RefreshToken" />
        <input id="Refresh" name="submit.Refresh" value="Refresh" type="submit" />
        <br />
        <br />
        <input id="CallApi" name="submit.CallApi" value="Access Protected Resource API" type="submit" />
    </div>
    <div>
        @ViewBag.ApiResponse
    </div>
</form>
使用Oauth2令牌

:  public void login()
    {
        string userName = "abc@mailinator.com";
        string password = "Pass@123";
        //var registerResult = Register(userName, password);

        //Console.WriteLine("Registration Status Code: {0}", registerResult);

        string token = GetToken(userName, password);
        Console.WriteLine("");
        Console.WriteLine("Access Token:");
        Console.WriteLine(token);


        Dictionary<string, string> tokenDic = GetTokenDictionary(token);

        GetUserInfo(tokenDic["access_token"]);

    }


    private const string baseUrl = "http://localhost/WebApplication4";
    static string GetToken(string userName, string password)
    {
        var pairs = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>( "grant_type", "password" ), 
            new KeyValuePair<string, string>( "userName", userName ), 
            new KeyValuePair<string, string> ( "password", password )
        };

        var content = new FormUrlEncodedContent(pairs);
        using (var client = new HttpClient())
        {
            var response = client.PostAsync(baseUrl + "/Token", content).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }


    static Dictionary<string, string> GetTokenDictionary(string token)
    {
        // Deserialize the JSON into a Dictionary<string, string>
        Dictionary<string, string> tokenDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(token);
        return tokenDictionary;
    }

    static HttpClient CreateClient(string accessToken = "")
    {
        var client = new HttpClient();
        if (!string.IsNullOrWhiteSpace(accessToken))
        {
            client.DefaultRequestHeaders.Authorization =
                new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
        }
        return client;
    }

    static string GetUserInfo(string token)
    {
        using (var client = CreateClient(token))
        {
            var response = client.GetAsync(baseUrl + "/api/Account/UserInfo").Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }
  <form id="form1" action="@ViewBag.Action" method="POST">
    <div>
        Access Token<br />
        <input id="AccessToken" name="AccessToken" width="604" type="text" value="@ViewBag.AccessToken" />
        <input id="Authorize" name="submit.Authorize" value="Authorize" type="submit" />
        <br />
        <br />
        Refresh Tokensh Token<br />
        <input id="RefreshToken" name="RefreshToken" width="604" type="text" value="@ViewBag.RefreshToken" />
        <input id="Refresh" name="submit.Refresh" value="Refresh" type="submit" />
        <br />
        <br />
        <input id="CallApi" name="submit.CallApi" value="Access Protected Resource API" type="submit" />
    </div>
    <div>
        @ViewBag.ApiResponse
    </div>
</form>
获取重新刷新令牌

  :  public ActionResult Index()
    {
        ViewBag.AccessToken = Request.Form["AccessToken"] ?? "";
        ViewBag.RefreshToken = Request.Form["RefreshToken"] ?? "";
        ViewBag.Action = "";
        ViewBag.ApiResponse = "";

        InitializeWebServerClient();
        var accessToken = Request.Form["AccessToken"];
        if (string.IsNullOrEmpty(accessToken))
        {
            var authorizationState = _webServerClient.ProcessUserAuthorization(Request);
            if (authorizationState != null)
            {
                ViewBag.AccessToken = authorizationState.AccessToken;
                ViewBag.RefreshToken = authorizationState.RefreshToken;
                ViewBag.Action = Request.Path;
            }
        }

        if (!string.IsNullOrEmpty(Request.Form.Get("submit.Authorize")))
        {
            var userAuthorization = _webServerClient.PrepareRequestUserAuthorization(new[] { "bio", "notes" });
            userAuthorization.Send(HttpContext);
            Response.End();
        }
        else if (!string.IsNullOrEmpty(Request.Form.Get("submit.Refresh")))
        {
            var state = new AuthorizationState
            {
                AccessToken = Request.Form["AccessToken"],
                RefreshToken = Request.Form["RefreshToken"]
            };
            if (_webServerClient.RefreshAuthorization(state))
            {
                ViewBag.AccessToken = state.AccessToken;
                ViewBag.RefreshToken = state.RefreshToken;
            }
        }
        else if (!string.IsNullOrEmpty(Request.Form.Get("submit.CallApi")))
        {
            var resourceServerUri = new Uri(Paths.ResourceServerBaseAddress);
            var client = new HttpClient(_webServerClient.CreateAuthorizingHandler(accessToken));
            var body = client.GetStringAsync(new Uri(resourceServerUri, Paths.MePath)).Result;
            ViewBag.ApiResponse = body;
        }

        return View();
    }

    private void InitializeWebServerClient()
    {
        var authorizationServerUri = new Uri(Paths.AuthorizationServerBaseAddress);
        var authorizationServer = new AuthorizationServerDescription
        {
            AuthorizationEndpoint = new Uri(authorizationServerUri, Paths.AuthorizePath),
            TokenEndpoint = new Uri(authorizationServerUri, Paths.TokenPath)
        };
        _webServerClient = new WebServerClient(authorizationServer, Clients.Client1.Id, Clients.Client1.Secret);
    }
}
获取重新刷新令牌

  :  public ActionResult Index()
    {
        ViewBag.AccessToken = Request.Form["AccessToken"] ?? "";
        ViewBag.RefreshToken = Request.Form["RefreshToken"] ?? "";
        ViewBag.Action = "";
        ViewBag.ApiResponse = "";

        InitializeWebServerClient();
        var accessToken = Request.Form["AccessToken"];
        if (string.IsNullOrEmpty(accessToken))
        {
            var authorizationState = _webServerClient.ProcessUserAuthorization(Request);
            if (authorizationState != null)
            {
                ViewBag.AccessToken = authorizationState.AccessToken;
                ViewBag.RefreshToken = authorizationState.RefreshToken;
                ViewBag.Action = Request.Path;
            }
        }

        if (!string.IsNullOrEmpty(Request.Form.Get("submit.Authorize")))
        {
            var userAuthorization = _webServerClient.PrepareRequestUserAuthorization(new[] { "bio", "notes" });
            userAuthorization.Send(HttpContext);
            Response.End();
        }
        else if (!string.IsNullOrEmpty(Request.Form.Get("submit.Refresh")))
        {
            var state = new AuthorizationState
            {
                AccessToken = Request.Form["AccessToken"],
                RefreshToken = Request.Form["RefreshToken"]
            };
            if (_webServerClient.RefreshAuthorization(state))
            {
                ViewBag.AccessToken = state.AccessToken;
                ViewBag.RefreshToken = state.RefreshToken;
            }
        }
        else if (!string.IsNullOrEmpty(Request.Form.Get("submit.CallApi")))
        {
            var resourceServerUri = new Uri(Paths.ResourceServerBaseAddress);
            var client = new HttpClient(_webServerClient.CreateAuthorizingHandler(accessToken));
            var body = client.GetStringAsync(new Uri(resourceServerUri, Paths.MePath)).Result;
            ViewBag.ApiResponse = body;
        }

        return View();
    }

    private void InitializeWebServerClient()
    {
        var authorizationServerUri = new Uri(Paths.AuthorizationServerBaseAddress);
        var authorizationServer = new AuthorizationServerDescription
        {
            AuthorizationEndpoint = new Uri(authorizationServerUri, Paths.AuthorizePath),
            TokenEndpoint = new Uri(authorizationServerUri, Paths.TokenPath)
        };
        _webServerClient = new WebServerClient(authorizationServer, Clients.Client1.Id, Clients.Client1.Secret);
    }
}

我认为没有必要使用ViewResolver!只消耗注释元素就足够了。我认为没有必要使用ViewResolver!仅使用注释元素就足够了。为此,我们需要添加任何依赖项…?是的,Spring 4。*,我更新了关于您问题的答案。对于Spring 4,请遵循以下指南:为此,我们需要添加任何依赖项…?是的,Spring 4。*,我更新了关于您问题的答案。对于Spring 4,请遵循以下指南: