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

标签 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");

适合安卓吗?

请指教。

最佳答案

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

相关文章:

java - 背靠背多个 HttpExchange,使用 com.sun.net.httpserver.HttpServer 从第一次交换开始清理

java - HttpURLConnection 和没有互联网

java.net.ProtocolException : Server redirected too many times (20)

Java HttpURLConnection - 枚举所有 302 重定向跃点

java - 如何使用 HttpURLConnection 让此 HTTP/1.1 POST 在 Java 中工作?

android - 在向上导航中的 Activity A 上调用 onCreate

android - 使用react-native测量音频的响度

Android:如何将预览帧保存为 jpeg 图像?

c# - native Xamarin.Android 应用程序在 Release模式下不断崩溃

android - 任何使捏合缩放更平滑的方法