如何在HttpURLConnection中设置Content Type?

51

你知道如何在 HttpURLConnection 上设置 Content-Type 吗?

下面的代码是在黑莓上的,我想要等效于Android的代码:

connection.setRequestProperty("content-type", "text/plain; charset=utf-8");
connection.setRequestProperty("Host", "192.168.1.36"); 
connection.setRequestProperty("Expect", "100-continue");

这是否适用于安卓系统?

请给出建议。


在寻找正确的头文件以指定GET请求时,通过查看您的问题得到了答案。 - Grubsnik
你好,我有一个关于你的话题的问题...你能告诉我一些关于"connection.setRequestProperty("Expect", "100-continue");"如何影响你的过程的一般想法吗?你需要像...等待100响应,然后执行其他操作,然后等待200响应吗? - Josh
2个回答

75
如果你真的想使用 HttpURLConnection,可以使用 setRequestProperty 方法,例如:
myHttpURLConnection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
myHttpURLConnection.setRequestProperty("Expect", "100-continue");

不过,如果我是你的话,我会考虑使用Apache HTTP库。它们更高级且易于使用。使用它们,你可以像下面这样做:

HttpGet get = new HttpGet("http://192.168.1.36/");
get.setHeader("Content-Type", "text/plain; charset=utf-8");
get.setHeader("Expect", "100-continue");

HttpResponse resp = null;
try {
    HttpClient httpClient = new DefaultHttpClient();
    resp = httpClient.execute(get);
} catch (ClientProtocolException e) {
    Log.e(getClass().getSimpleName(), "HTTP protocol error", e);
} catch (IOException e) {
    Log.e(getClass().getSimpleName(), "Communication error", e);
}
if (resp != null) {
    // got a response, do something with it
} else {
    // there was a problem
}

10
建议您按照 Jesse Wilson 的建议,使用 UrlConnection 进行开发,详情请参考 http://android-developers.blogspot.com/2011/09/androids-http-clients.html。 - Chris.Jenkins
1
注意未来的人,@Chris.Jenkins 是正确的。截至本回答时,Apache库优于其他库,但在之后的版本中可能有所改变。 - Jeremy Logan
我该如何在Java中使用HTTP POST方法发送作用域?我需要通过发送作用域、ID密码和凭据来生成令牌。我无法获取任何代码。 - user9892866

16
connection.setRequestProperty("Content-Type", "VALUE");

感谢您的快速回复。我有一个问题?我正在尝试创建HTTP GET连接:connection.setRequestProperty("content-type", "text/plain; charset=utf-8"); connection.setRequestProperty("Host", "192.168.1.36"); connection.setRequestProperty("Expect", "100-continue");这对于Android来说是正确的吗? - AndroiDBeginner
对安卓不太了解。另外,请查看您的问题下的评论。 - Rites

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接