如何在HttpURLConnection上设置内容types?

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

下面的代码是在黑莓上,我想要Android的等效:

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

是否适合android?

请指教。

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

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

但是,如果我是你,我会考虑使用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 } 
 connection.setRequestProperty("Content-Type", "VALUE");