- HTTP заголовки | Тип содержимого
- HTTP headers | Content-Type
- Android http content type
- Android OkHttp Example
- OkHttp Supports Http/2
- Features of OkHttp.
- Add Library to Project
- Add Permission to Manifest
- Android OkHttp Examples
- Android OkHttp Get Example
- Android OkHttp Get Request With Query String Example
- Android OkHttp Post Example
- Android OkHttp POST JSON Example
- Android OkHttp Headers Example
- Android OkHttp Async Call
- Android OkHttp Multipart Example
- Android OkHttp Example Code
- Activity
- Layout
- About
- Android HTTP Client: GET, POST, Download, Upload, Multipart Request
- GET and POST requests in Android HTTP Client
- Download data from server to Android app
- Upload data to the server using MultipartRequest
HTTP заголовки | Тип содержимого
Заголовок Content-Type используется для указания типа мультимедиа ресурса. Тип носителя — это строка, отправляемая вместе с файлом с указанием формата файла. Например, для файла изображения его тип носителя будет таким, как image / png или image / jpg и т. Д.
В ответ он сообщает о типе возвращаемого контента клиенту. Браузер узнает о типе контента, который он должен загрузить на компьютер. Каждый раз, когда его байтовый поток файла, который получают браузеры, с помощью заголовка Content-type, браузер будет делать что-то, известное как сниффинг MIME, то есть он будет проверять поток, который он получает, и затем соответствующим образом загружает данные.
Синтаксис:
Директивы: в заголовках HTTP есть три директивы Content-type.
- Тип носителя: он содержит тип данных MIME (Multipurpose Internet Mail Extensions).
- charset: содержит стандарт кодировки символов. Charset — это стандарт кодирования, в котором данные будут приниматься браузерами.
- border: Директива границы обязательна, когда есть составные объекты. Граница предназначена для составных объектов, состоящих из 70 символов из набора символов, которые, как известно, очень устойчивы в почтовых шлюзах и не имеют пробелов.
Пример. В этом примере показано, как изображения читаются браузером с настройкой заголовка типа контента и без него.
header( ‘Content-type: image/jpeg’ ); // с заголовком Тип содержимого
Выход :
Теперь, не используя заголовок Content-type, мы получим содержимое изображения в байтах, поэтому оно нам не нужно.
Здесь ясно видно, что, применяя информацию заголовка Content-type, сообщает браузеру, тип ответа, который он получает от сервера.
Все возможные значения заголовка HTTP Content-type:
Type | Values |
---|---|
Application | application/EDI-X12 application/EDIFACT application/javascript application/octet-stream application/ogg application/pdf application/xhtml+xml application/x-shockwave-flash application/json application/ld+json application/xml application/zip application/x-www-form-urlencoded |
Audio | audio/mpeg audio/x-ms-wma audio/vnd.rn-realaudio audio/x-wav |
Image | image/gif image/jpeg image/png image/tiff image/vnd.microsoft.icon image/x-icon image/vnd.djvu image/svg+xml |
Multipart | multipart/mixed multipart/alternative multipart/related (using by MHTML (HTML mail).) multipart/form-data |
Text | text/css text/csv text/html text/javascript (obsolete) text/plain text/xml |
Video | video/mpeg video/mp4 video/quicktime video/x-ms-wmv video/x-msvideo video/x-flv video/webm |
VND | application/vnd.oasis.opendocument.text application/vnd.oasis.opendocument.spreadsheet application/vnd.oasis.opendocument.presentation application/vnd.oasis.opendocument.graphics application/vnd.ms-excel application/vnd.openxmlformats-officedocument.spreadsheetml.sheet application/vnd.ms-powerpoint application/vnd.openxmlformats-officedocument.presentationml.presentation application/msword application/vnd.openxmlformats-officedocument.wordprocessingml.document application/vnd.mozilla.xul+xml |
Поддерживаемые браузеры: браузеры, совместимые с заголовками HTTP, Content-type перечислены ниже:
- Гугл Хром
- Internet Explorer
- Fire Fox
- Сафари
- опера
Источник
HTTP headers | Content-Type
The Content-Type header is used to indicate the media type of the resource. The media type is a string sent along with the file indicating the format of the file. For example, for image file its media type will be like image/png or image/jpg, etc.
In response, it tells about the type of returned content, to the client. The browser gets to know about the type of content it has to load on the machine. Every time its byte stream of the file that browsers receive, by the Content-type header, the browser will do something known as MIME sniffing i.e. it will inspect the stream it is receiving and then loads the data accordingly.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
Syntax:
Directives: There are three directives in the HTTP headers Content-type.
Example: This example display how the images are read by browser with and without setting the Content-type header.
Output :
Now without using Content-type header we will get the content of the image in bytes, So it is not of any use to us.
Here, it is clearly visible that by applying the Content-type header information tells the browser, the type of response it is getting from the server.
All possible values of HTTP Content-type header:
Type | Values |
---|---|
Application | application/EDI-X12 application/EDIFACT application/javascript application/octet-stream application/ogg application/pdf application/xhtml+xml application/x-shockwave-flash application/json application/ld+json application/xml application/zip application/x-www-form-urlencoded |
Audio | audio/mpeg audio/x-ms-wma audio/vnd.rn-realaudio audio/x-wav |
Image | image/gif image/jpeg image/png image/tiff image/vnd.microsoft.icon image/x-icon image/vnd.djvu image/svg+xml |
Multipart | multipart/mixed multipart/alternative multipart/related (using by MHTML (HTML mail).) multipart/form-data |
Text | text/css text/csv text/html text/javascript (obsolete) text/plain text/xml |
Video | video/mpeg video/mp4 video/quicktime video/x-ms-wmv video/x-msvideo video/x-flv video/webm |
VND | application/vnd.oasis.opendocument.text application/vnd.oasis.opendocument.spreadsheet application/vnd.oasis.opendocument.presentation application/vnd.oasis.opendocument.graphics application/vnd.ms-excel application/vnd.openxmlformats-officedocument.spreadsheetml.sheet application/vnd.ms-powerpoint application/vnd.openxmlformats-officedocument.presentationml.presentation application/msword application/vnd.openxmlformats-officedocument.wordprocessingml.document application/vnd.mozilla.xul+xml |
Supported Browsers: The browsers compatible with HTTP headers Content-type are listed below:
- Google Chrome
- Internet Explorer
- Firefox
- Safari
- Opera
Источник
Android http content type
Android OkHttp Example
May 27, 2017 by Srinivas
Android apps rely on rest services running on server for authentication & authorization, getting and posting data. Since the services on the web run on http protocol, in order to network with servers, android apps need http client. While there are several http client libraries and frameworks including volley which can be used in Android, OkHttp, an Http & Http/2 client, is widely used in android and java applications.
In this article, I am going to explain features of OkHttp and show how to use OkHttp in android to make http get, post, multipart, json and asynchronous request calls with examples.
OkHttp Supports Http/2
Below are some of the features of http/2
- Http/2 is a binary protocol which is more efficient compared to text protocol Http.
- Http/2 supports multiplexing meaning multiple requests and responses can be in flight at the same time on a connection.
- Http/2 supports header compression leading to reduced network round trips.
- Http/2 provides improved security.
Features of OkHttp.
OkHttp supports below features which make OkHttp an efficient http client with fast loading and reduced network bandwidth.
- OkHttp supports Http/2 protocol.
- Connection pooling can used for http protocol connections.
- GZIP compression shrinks network data size.
- Cache eliminates network round trip for repeating requests.
- OkHttp silently recovers from network problems.
- If your server is load balanced, OkHttp tries to connect other nodes when it fails to connect one of the nodes in load balancer.
- OkHttp supports both synchronous and asynchronous calls.
- You can use OkHttp on Android 2.3 and Java 7 versions onwards.
Add Library to Project
You can add OkHttp library to your project by adding below line to your module gradle property file.
Add Permission to Manifest
As below examples access rest services on server, internet permission is required. Add below permission to manifest xml file.
Android OkHttp Examples
In the below examples, the process of making reset service calls and updating UI with responses is executed in the background thread using AsyncTask. I provided below detailed explanation of each type of http request and complete android OkHttp example code.
Android OkHttp Get Example
Below code shows how to send http get request using OkHttp. To make an http get request call using OkHttp, you need to create Request object by using Request.Builder. Then call newCall method on OkHttpClient object passing the Request object. Finally, call execute() method on Call object to make http get request and receive response.
Above service call returns response in JSON format. Once you get JSON string from response by calling response.body().string(), you can use JSONOjbect or gson for parsing it. If you need more information on how to parse json in android, you can view my previous posts parsing JSON using JSONObject and parsing Json using gson library.
Android OkHttp Get Request With Query String Example
To make http get request call with query parameter using OkHttp, you need to use HttpUrl.Builder and add query parameter to it by calling addQueryParameter on HttpUrl.Builder as shown in below code.
Android OkHttp Post Example
To add post data to Request as key value pairs like data from html forms, you need to use FormBody.Builder, add post parameters to it, and create RequestBody as shown below.
Android OkHttp POST JSON Example
You can post json string to server using OkHttp. To do that, you need to create RequestBody object using create method on RequestBody passing json MediaType and json string as show below.
Android OkHttp Headers Example
You can add headers to request when request object is created or in intercepters by calling addHeader method on Request.Builder object.
Android OkHttp Async Call
In our examples, as UI needs to be updated with response after service call, entire process of making service calls and updating UI is done in the background using AsyncTask. But if you don’t need to use AsyncTask but only want to make http call asynchronously, you can do so by calling enqueue method on Call object passing Callback instead of execute method which makes http call synchronously.
Android OkHttp Multipart Example
To upload files or send multiple parts to http server, you need to send http multipart request. You can create multipart requests in OkHttp by building RequestBody using MultipartBody.Builder shown below. MultipartBody.Builder allows you to add data parts using addFormDataPart method.
Android OkHttp Example Code
Activity
Layout
About
Android app development tutorials and web app development tutorials with programming examples and code samples.
Источник
Android HTTP Client: GET, POST, Download, Upload, Multipart Request
Often Android apps have to exchange information with a remote server using Android HTTP client. The easiest way is to use the HTTP protocol as a base to transfer information. There are several scenarios where the HTTP protocol is very useful like downloading an image from a remote server or uploading some binary data to the server. Android app performs GET or POST request to send data. In this post, we want to investigate how to use HttpURLConnection to communicate with a remote server.
As a server, we will use three simple Servlet running inside Tomcat 7.0. We won’t cover how to create a Servlet using API 3.0, you can find the source code here.
You can download the tutorial source code here:
GET and POST requests in Android HTTP Client
When developing Android HTTP client, GET and POST requests are the base blocks in HTTP protocol. To make this kind of requests we need first to open a connection toward the remote server:
[java] HttpURLConnection con = (HttpURLConnection) ( new URL(url)).openConnection();
con.setRequestMethod(«POST»);
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
[/java]
In the first line we get the HttpURLConnection, while in line 2, we set the method and at the end we connect to the server.
Once we have opened the connection we can write on it using the OutputStream.
As we already know parameters are written using key-value pair.
The last step is reading the response, using the InputStream:
[java]InputStream is = con.getInputStream();
byte[] b = new byte[1024];
while ( is.read(b) != -1)
buffer.append(new String(b));
con.disconnect();[/java]
Everything is very simple by now, but we have to remember one thing: when android HTTP client makes an HTTP connection, this operation is a time- consuming operation that could require a long time, sometime so we can’t run it on the main thread otherwise we could get a ANR problem. To solve it we can use an AsyncTask.
@Override
protected void onPostExecute(String result) <
edtResp.setText(result);
item.setActionView(null);
>
>[/java]
Running the app we get:
As we can see we post a name to the server and it responds with the classic ‘Hello….’. On the server side we can check that the server received correctly our post parameter:
Download data from server to Android app
One of the most common scenario when developing Android HTTP client is when an Android App has to download some data from a remote server. We can suppose that we want to download an image from the server. In this case we have always to use an AsyncTask to complete our operation, the code is shown below:
[java]public byte[] downloadImage(String imgName) <
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try <
System.out.println(«URL [«+url+»] – Name [«+imgName+»]»);
HttpURLConnection con = (HttpURLConnection) ( new URL(url)).openConnection();
con.setRequestMethod(«POST»);
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
con.getOutputStream().write( («name=» + imgName).getBytes());
InputStream is = con.getInputStream();
byte[] b = new byte[1024];
while ( is.read(b) != -1)
baos.write(b);
con.disconnect();
>
catch(Throwable t) <
t.printStackTrace();
>
return baos.toByteArray();
>[/java]
This method is called in this way:
[java] private class SendHttpRequestTask extends AsyncTask&amp;amp;lt;String, Void, byte[]&amp;amp;gt; <
@Override
protected byte[] doInBackground(String… params) <
String url = params[0];
String name = params[1];
HttpClient client = new HttpClient(url);
byte[] data = client.downloadImage(name);
@Override
protected void onPostExecute(byte[] result) <
Bitmap img = BitmapFactory.decodeByteArray(result, 0, result.length);
imgView.setImageBitmap(img);
item.setActionView(null);
>
>
[/java]
Running the app we have:
Upload data to the server using MultipartRequest
This the most complex part in developing Android HTTP client is handling HTTP connection. Natively HttpURLConnection doesn’t handle this type of request. It can happen that an Android App has to upload some binary data to the server. It can be that an app has to upload an image for example. In this case,the request gets more complex, because a “normal” request isn’t enough. We have to create a MultipartRequest.
A MultipartRequest is a request that is made by different parts as parameters and binary data. How can we handle this request?
Well the first step is opening a connection informing the server we want to send some binary info:
[java] public void connectForMultipart() throws Exception <
con = (HttpURLConnection) ( new URL(url)).openConnection();
con.setRequestMethod(«POST»);
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty(«Connection», «Keep-Alive»);
con.setRequestProperty(«Content-Type», «multipart/form-data; boundary=» + boundary);
con.connect();
os = con.getOutputStream();
>[/java]
In lines 6 and 7, we specify the request content-type and another field called boundary. This field is a char sequence used to separate different parts.
For each part, we want to add we need to specify if it is text part like post parameter or it is a file (so binary data).
[java] public void addFormPart(String paramName, String value) throws Exception <
writeParamData(paramName, value);
>
private void writeParamData(String paramName, String value) throws Exception <
os.write( (delimiter + boundary + «rn»).getBytes());
os.write( «Content-Type: text/plainrn».getBytes());
os.write( («Content-Disposition: form-data; name=»» + paramName + «»rn»).getBytes());;
os.write( («rn» + value + «rn»).getBytes());
>[/java]
[java]private String delimiter = «–»;
private String boundary = «SwA»+Long.toString(System.currentTimeMillis())+»SwA»;
[/java]
To add a file part we can use:
[java] public void addFilePart(String paramName, String fileName, byte[] data) throws Exception <
os.write( (delimiter + boundary + «rn»).getBytes());
os.write( («Content-Disposition: form-data; name=»» + paramName + «»; filename=»» + fileName + «»rn» ).getBytes());
os.write( («Content-Type: application/octet-streamrn» ).getBytes());
os.write( («Content-Transfer-Encoding: binaryrn» ).getBytes());
os.write(«rn».getBytes());
So in our app we have:
[java] private class SendHttpRequestTask extends AsyncTask&amp;amp;lt;String, Void, String&amp;amp;gt; <
@Override
protected String doInBackground(String… params) <
String url = params[0];
String param1 = params[1];
String param2 = params[2];
Bitmap b = BitmapFactory.decodeResource(UploadActivity.this.getResources(), R.drawable.logo);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
b.compress(CompressFormat.PNG, 0, baos);
try <
HttpClient client = new HttpClient(url);
client.connectForMultipart();
client.addFormPart(«param1», param1);
client.addFormPart(«param2», param2);
client.addFilePart(«file», «logo.png», baos.toByteArray());
client.finishMultipart();
String data = client.getResponse();
>
catch(Throwable t) <
t.printStackTrace();
>
@Override
protected void onPostExecute(String data) <
item.setActionView(null);
>
Running it we have:
At the end of this post, you know how to handle HTTP connections using Android and how to send and retrieve data using standard HTTP library shipped with Android.
Источник