JAVA-处理HttpClient对内容类型的请求:application/json



希望每个人都做得很好。

问题:每次我通过POST请求调用api登录时,我都会得到以下响应

[status] => 415
[error] => Unsupported Media Type
[message] => Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

这是我的Yii2应用程序端:代码

$url = ['auth/login'];
$data = ['email'=>$email, 'password'=>$password];
$response = Yii::$app->apiclient->createRequest()
->setMethod('post')
->setUrl($url)
->addHeaders(['Accept-Charset' => 'UTF-8'])
->addHeaders(['Accept' => 'application/json'])
->addHeaders(['Content-Type' => 'application/json'])
->addHeaders(['Accept-Language' => apphelpersHelper::getUserLanguage()])
->setData($data)
->send();
return $response;

以下是我的apiclient设置在组件部分下的web.conf文件中

'apiclient' => [
'class' => 'yiihttpclientClient',
'baseUrl' => 'http://myserverName:8000',
],

这是我为Spring(JAVA(API端:编写的代码

@RequestMapping(value = "/auth/login", method = RequestMethod.POST)
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {}

目标:如果登录凭据(电子邮件和密码(正确,我想从api获取用户数据。或者甚至验证错误消息也会进行

上下文:我使用Yii2框架作为我的应用程序(前端(,使用Spring(JAVA(作为我的后端(API(

旁注:有趣的是,我甚至没有尝试内容类型application/x-www-form-urlencode,正如你在我的Yii2代码中看到的那样,但我仍然得到了问题中提到的响应。

另一个有趣的事实是,当我在邮递员中调用相同的API时,我不会得到任何错误,我的响应完全是应该的

感谢您的帮助。

将此添加到您的请求中:

->setFormat(\yii\httpclient\Client::FORMAT_JSON(

试试这个:

@RequestMapping(value = "/auth/login", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest, BindingResult bindingResult) {}

这可能会对你有所帮助。。

谢谢:(

问题是我发送给api的请求。

以下是我需要做的

$response = Yii::$app->apiclient->createRequest()
->setMethod('POST')
->setUrl($url)
->setData($data)
->setFormat(yiihttpclientClient::FORMAT_JSON)
->addHeaders(['accept-charset' => 'utf-8'])
->addHeaders(['accept' => 'application/json'])
->addHeaders(['content-type' => 'application/json'])
->addHeaders(['accept-language' => apphelpersHelper::getUserLanguage()])
->send();

我添加了以下行,它起到了的作用

->setFormat(yiihttpclientClient::FORMAT_JSON)

注意

我不知道它是如何以及为什么工作的,但这可能是因为PHP是一种松散类型的语言,而JAVA则相反。Java会要求发送所有次要的细节,以便处理请求。

相关内容

最新更新