简体   繁体   English

如何从URLConnection删除标头

[英]how to remove a header from URLConnection

I am talking to a file upload service that accepts post data, not form data. 我说的是一种文件上传服务,该服务接受发布数据,而不接受表单数据。 By default, java's HttpURLConnection sets the Content-Type header to application/x-www-form-urlencoded . 默认情况下,java的HttpURLConnectionContent-Type标头设置为application/x-www-form-urlencoded this is obviously wrong if i'm posting pure data. 如果我发布纯数据,这显然是错误的。

I (the client) don't know the content type. 我(客户)不知道内容类型。 I don't want the Content-Type header set at all. 我根本不需要设置Content-Type标头。 the service has a feature where it will guess at the content type (based on the file name, reading some data from the file, etc). 该服务具有一项功能,可以猜测内容类型(基于文件名,从文件中读取一些数据等)。

How do I unset a header? 如何取消设置标题? There's no remove header, and setting it to null doesn't change the value and setting it to the empty string results in the header being set with no value. 没有删除标头,将其设置为null不会更改值,将其设置为空字符串会导致标头设置为无值。

Use Apache HttpClient instead of URLConnection 使用Apache HttpClient代替URLConnection

Use fluent Request to generate your request 使用流利的请求来生成您的请求

use removeHeader() 使用removeHeader()

I haven't tested this approach but you can try this: 我尚未测试这种方法,但是您可以尝试以下方法:

Extend HttpURLConnection and try by overriding its getContentHandler() and setContentHandler(...) methods. 扩展HttpURLConnection并尝试覆盖其getContentHandler()和setContentHandler(...)方法。 Most probably this should work as, you will take a look at code of getContentHandler(). 这很可能应该起作用,因为您将看一下getContentHandler()的代码。

What do you mean "i don't want the Content-Type header to set at all"? 您是什么意思“我根本不想设置Content-Type标头”?

The browser (or other http client) sends your post request to the server, so it has to inform the server which way it encoded the parameters. 浏览器(或其他http客户端)将您的发布请求发送到服务器,因此它必须通知服务器它对参数进行编码的方式。

If the Content-Type header is not set, on the server side you (= your server) won't be able to understand how to parse the received data. 如果未设置Content-Type标头,则在服务器端,您(=服务器)将无法理解如何解析接收到的数据。

If you didn't set Content-Type, the default value will be used. 如果您未设置Content-Type,则将使用默认值。

You browser (or other http client) MUST do two things: 您的浏览器(或其他http客户端)必须做两件事:

  1. Send key/value pairs. 发送键/值对。
  2. Inform the server how the key/value pairs were encoded. 通知服务器键/值对的编码方式。

So, it is impossible to completely get rid of this header. 因此,不可能完全摆脱此标头。

我只是通过将标头设置为null来完成此操作。

connection.setRequestProperty(MY_HEADER, null);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM