【问题标题】:HTTP 400 Bad Request - Invalid Header with Retrofit on AndroidHTTP 400 错误请求 - Android 上带有改造的无效标头
【发布时间】:2014-01-22 00:39:45
【问题描述】:

我正在使用OkHttp 将我的Android 项目从Apache HttpClient 迁移到Retrofit。 POST/PUT 请求返回错误,即使应用程序自定义标头相同且两个请求的 Content-Length 相同。

  • GET:工作正常。
  • POST/PUT:Http Error 400 Bad Request - Invalid Header。即使

作为参考,服务器是在Windows Azure上使用ASP.NET实现的。

Apache HttpClient

HttpPut put = new HttpPut(<URL>);
StringEntity se = new StringEntity(json);
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
put.setEntity(se);
response = client.execute(put);

改造 + OkHttp

// API
@PUT("/<path>")
Response updateThing(@Body Dto dto);

// OkHttpClient
@Override
public Response execute(Request r) throws IOException {
    List<Header> headers = HttpHelper.headerFor(method, url, etc);

    // Create new request with required headers
    Request encodedRequest = new Request(method, url, headers, r.getBody());
    return super.execute(encodedRequest);
}

服务器返回:

---> HTTP PUT https://example.com/path
Content-Type: application/json; charset=UTF-8
Content-Length: 53
{"user_id":"0","latitude":"0.0","longitude":"0.0"}
---> END HTTP (53-byte body)
PUT https://example.com/path
Authorization Basic bmfweEskWkvlabF0ZSQ=
Content-Type application/json
Accept application/json
HashKey 8eb93b898ddc2b74685ed2be64c76cc3af973ebc6b628781fe50eedcbe29376f
<--- HTTP 400 https://example.com/path (1397ms)
: HTTP/1.1 400 Bad Request
Connection: close
Content-Length: 339
Content-Type: text/html; charset=us-ascii
Date: Sat, 04 Jan 2014 08:26:45 GMT
OkHttp-Received-Millis: 1388824004870
OkHttp-Response-Source: NETWORK 400
OkHttp-Selected-Transport: http/1.1
OkHttp-Sent-Millis: 1388824004785
Server: Microsoft-HTTPAPI/2.0

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Header</h2>
<hr><p>HTTP Error 400. The request has an invalid header name.</p>
</BODY></HTML>

<--- END HTTP (339-byte body)

编辑

  • 使用在线 Hurl.it 发送 POST/PUT 请求有效。
  • 也可以使用 Retrofit 发送没有任何正文的 POST/PUT 请求。

【问题讨论】:

  • 是您的帖子还是某些标题没有':'分隔符
  • @EugenMartynov 谢谢!这是重复的 Content-Type 标头。
  • 太棒了!有时这样的小错误会阻止我们几个小时

标签: android asp.net apache-httpclient-4.x bad-request retrofit


【解决方案1】:

不确定服务器期望什么作为标头参数,但您可以在客户端接口上传递任何标头值

@PUT("/<path>")
Response updateThing(@Header("headerName") String headerName, @Body Dto dto);

【讨论】:

  • 哈希的东西是根据http方法、url和参数本身创建的,所以我使用请求拦截的方法而不是@Header注解。
猜你喜欢
  • 2016-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
  • 2020-09-02
  • 2014-12-11
  • 2019-04-12
  • 1970-01-01
相关资源
最近更新 更多