首页 > 解决方案 > 为什么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/jsonapplication/x-www-form-urlencoded,但仍然无法解决。

我尝试调用一个Get方法,没关系。

为什么 Post 方法出现错误 [不支持 HTTP 请求中指定的 Content-Type 标头]?

标签: androidsalesforce

解决方案


我想提出一个更好的解决方案。改造库

尽管不是强制使用 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相关的依赖关系。

由于不宜从对应的Retrofit依赖和示例代码入手,具体可参考参考一参考二


推荐阅读