2009-12-22 72 views
38

你知道如何设置Content-TypeHttpURLConnection如何在HttpURLConnection上设置内容类型?

下面的代码是在黑莓和我想在Android相当于:

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

是否适合Android的?

请指教。

+0

正在寻找正确的标题来指定一个GET请求,所以通过查看你的问题来回答我的问题。 – Grubsnik 2010-11-12 09:20:16

+0

嗨,我有一个问题涉及到你的话题...你能告诉我一些关于如何“connection.setRequestProperty(”期待“,”100-继续“)的一般想法;”影响你的程序?你需要......等待100响应,然后做其他一些操作,然后等待200响应? – Josh 2015-12-12 19:05:16

回答

59

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

真的如建议您应该使用Jesse Wilson建议的UrlConnection - http://android-developers.blogspot.com/2011/09/androids-http-clients.html – 2011-10-17 09:31:53

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

感谢您的快速回复。 我有问题吗?我想创建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 2009-12-22 10:17:36

+0

没有太多的android知识。 此外,请参阅您的问题评论。 – Rites 2009-12-22 10:21:52