Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Content Type on HttpURLConnection?

Do you know how to set Content-Type on HttpURLConnection?

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

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.

like image 446
AndroiDBeginner Avatar asked Dec 22 '09 09:12

AndroiDBeginner


People also ask

How do I set media type in HttpURLConnection?

HttpURLConnection connection = (HttpURLConnection) new URL(url). openConnection(); connection. setRequestProperty( "Content-Type" , "application/x-www-form-urlencoded" );

How do I set headers in HttpURLConnection?

URL url = new URL(urlToConnect); HttpURLConnection httpUrlConnection = (HttpURLConnection) url. openConnection(); Step 2: Add headers to the HttpURLConnection using setRequestProperty method.

What is the difference between URLConnection and HttpURLConnection?

URLConnection is the base class. HttpURLConnection is a derived class which you can use when you need the extra API and you are dealing with HTTP or HTTPS only. HttpsURLConnection is a 'more derived' class which you can use when you need the 'more extra' API and you are dealing with HTTPS only.


2 Answers

If you really want to use the HttpURLConnection you can use the setRequestProperty method like:

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:

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 } 
like image 106
Jeremy Logan Avatar answered Sep 21 '22 15:09

Jeremy Logan


connection.setRequestProperty("Content-Type", "VALUE"); 
like image 20
Rites Avatar answered Sep 21 '22 15:09

Rites