android - 为什么okhttp的Post方法出现错误[不支持HTTP请求中指定的Content-Type标头:application/x-www-form-urlencoded]?
问题描述
我通过 post 方法调用了 salesforce 的 Rest API:
url = "https://test-dev-ed.my.salesforce.com/services/apexrest/AccountUsers/"
client = OkHttpClient()
val jsonIn = FormBody.Builder()
.add("email",URLEncoder.encode("dt1@gmail.com", "UTF-8"))
.add("password", URLEncoder.encode("1","UTF-8"))
.build()
request = Request.Builder()
.post(jsonIn)
.header("Authorization", "Bearer "+accesstoken)
.addHeader("Content-Type","application/x-www-form-urlencoded")
.url(url)
.build()
response = client.newCall(request).execute()
这是休息api:
@HttpPost
global static ID createUser(String email, String password) {
AccountUser__c us=new AccountUser__c();
us.Email__c=email;
us.Password__c=password;
us.Status__c=0;
insert us;
return us.Id;
}
但是结果返回是错误的:
[{"errorCode":"UNSUPPORTED_MEDIA_TYPE","message":"Content-Type header specified in HTTP request is not supported: application/x-www-form-urlencoded"}]
我曾尝试更改application/json
为application/x-www-form-urlencoded
,但仍然无法解决。
我尝试调用一个Get
方法,没关系。
为什么 Post 方法出现错误 [不支持 HTTP 请求中指定的 Content-Type 标头]?
解决方案
我想提出一个更好的解决方案。改造库
尽管不是强制使用 Retrofit,但这些都是一些引人注目的方面,使其在您的类似用例中可靠且方便。
为什么要使用改造?
- 类型安全的 REST 适配器,使常见的网络任务变得简单
- 对于
POST
操作,改造有助于组装需要提交的内容。例如:- 生成 URL 编码形式。 - 负责 URL 操作、请求、加载、缓存、线程、同步、同步/异步调用
- 使用与特定 REST API 相关的类型感知生成代码帮助生成 URL
- 解析
JSON
使用GSON
- Retrofit 是一个封装的 API 适配器
OkHttp
您面临的问题可以通过这样的改造来解决。
public interface APIConfiguration{
@Headers({"Accept:application/json",
"Content-Type:application/x-www-form-urlencoded"})
@FormUrlEncoded
@POST("user/registration")
Observable<DataPojo> registrationAPI(@FieldMap(encoded = true) Map<String, String> params);
}
就是这样,库只需要很少的注释就可以处理
Form URL Encoding
相关的依赖关系。
推荐阅读
- sql-server - 数据库备份到 Azure url - SQL Server 2014
- javascript - 如何制作 React Material UI
100% 宽度 - vba - VBA Word:在word文档中找到的文本之前插入文本
- postgresql-9.4 - 错误:运算符不存在:没有时区的时间戳 - bigint。- ( a.DURATION
- timeout - Tera Term Language:等待不等待超时结束
- angular - Angular 6 使用服务在组件之间共享数据
- python - 错误:需要 Microsoft Visual c++ 14.0,在 pip 安装 Numpy 时抛出
- spring-boot - 在 spring-boot:build-image 中通过命令行传递 dockerPublisher maven 属性
- reactjs - 在 React 应用程序中关闭选项卡后用户注销
- c# - dotnet 4.5 上的 Microsoft MVC 4 中是否有控制 JSON 消息复杂性的设置