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

And*_*ner 45 android httpurlconnection

你知道如何设置Content-Type的HttpURLConnection的?

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

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

它适合Android吗?

请指教.

Jer*_*gan 68

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

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

但是,如果我是你,我会考虑使用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
}
Run Code Online (Sandbox Code Playgroud)

  • 真的按照建议你应该使用Jesse Wilson建议的UrlConnection - http://android-developers.blogspot.com/2011/09/androids-http-clients.html (10认同)

Rit*_*tes 14

connection.setRequestProperty("Content-Type", "VALUE");
Run Code Online (Sandbox Code Playgroud)