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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1945336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:53:52  来源:igfitidea点击:

How to set Content Type on HttpURLConnection?

androidhttpurlconnection

提问by AndroiDBeginner

Do you know how to set Content-Typeon HttpURLConnection?

你知道如何设置Content-TypeHttpURLConnection的

Following code is on Blackberry and I want the Android equivalent:

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

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

Is it right for android?

适合安卓吗?

Please advise.

请指教。

回答by Jeremy Logan

If you really want to use the HttpURLConnectionyou can use the setRequestPropertymethod like:

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

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

However, if I were you I'd look into using the Apache HTTP libraries. They're a little higher-level and easier to use. With them you would do it with something like:

但是,如果我是您,我会考虑使用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
}

回答by Rites

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