如何在HttpURLConnection上设置内容类型?

时间:2009-12-22 09:57:43

标签: android httpurlconnection

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

以下代码在Blackberry上,我想要Android等价物:

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

适合安卓吗?

请告知。

2 个答案:

答案 0 :(得分:67)

如果您真的想使用HttpURLConnection,可以使用setRequestProperty方法,例如:

myHttpURLConnection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
myHttpURLConnection.setRequestProperty("Expect", "100-continue");

但是,如果我是你,我会考虑使用Apache HTTP libraries。它们更高级,更易于使用。有了它们,你可以用以下的东西来做:

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
}

答案 1 :(得分:14)

connection.setRequestProperty("Content-Type", "VALUE");
相关问题