gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-28 23:52:16 25 4
gpt4 key购买 nike

你知道如何在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");

适合安卓吗?

请指教。

最佳答案

如果你真的想使用 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
}

关于android - 如何在 HttpURLConnection 上设置内容类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1945336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com