[Computer Network Notes 7] Application Layer (4) HTTP method of submitting data through Content-Type

1. Content-Type: application/x-www-form-urlencodedIndicates the plain text form submission method

The format is as follows:

POST /users HTTP/1.1 
Host: api.github.com
Content-Type: application/x-www-form-urlencoded 
Content-Length: 27

name=zhangsan&gender=male 

Corresponding Retrofit code:

@FormUrlEncoded
@POST("/users")
Call<User> addUser(@Field("name") String name, @Field("gender") String gender);

It is also possible to use this type for GET requests.

2. Content-Type: multipart/form-data;boundary=[分隔符]Multi-text form submission method containing files

The format is as follows:

POST /home/upload.html HTTP/1.1
Accept: text/plain, */*
Accept-Language: zh-cn
Host: 192.168.24.56
Content-Type:multipart/form-data;boundary=-----------------------------7db372eb000e2
Content-Length: 3693
Connection: Keep-Alive

-------------------------------7db372eb000e2
Content-Disposition: form-data; name=“username”

admin
----------------------------------7db372eb000e2
Content-Disposition: form-data; name="file"; filename=" kn.jpg”
Content-Type: image/jpeg
(JPEG file binary data is omitted here...)

-------------------------------- --7db372eb000e2–

Note this line: According to RFC1867, the field is requiredContent-Type: multipart/form-data; boundary=---------------------------7db372eb000e2 in this way . It includes a flag named , which can be a string entered at will. It is also necessary for the specific content that follows . It is used to identify the beginning of a piece of content .Content-Type:multipart/form-databoundary

Content-Length: 3693 , where 3693 is the total length of the file to be uploaded.

The green font part is the data that needs to be uploaded, which can be text, pictures, etc. The data content needs to be preceded by description fields such as Content-Disposition , Content-Type and Content-Transfer-Encoding .

The last purple part is the end of the agreement.

---------------------------7db372eb000e2Is a separator that separates multiple files and form items. where b372eb000e2is a number generated on the fly to ensure that the entire delimiter does not appear in the content of the file or form item.

Each part of the Form is separated by a delimiter. --The two characters " " must be added before the delimiter --{boundary}to be considered by the http protocol as the delimiter of the Form. To indicate the end, add " --" after the correct delimiter to indicate the end. (i.e. --{boundary}--).

The front ---------------------------7dis a unique logo of IE, and Mozila is---------------------------71

Each separated data can use Content-Type to indicate the type of the following data. You can refer to rfc1341 for example: Contect-Type:image/jpegindicating that the following data is jpegfile data.

Corresponding Retrofit code:

@Multipart
@POST("/users")
Call<User> addUser(@Part("name") RequestBody name, @Part("avatar") RequestBody avatar);
...
RequestBody namePart = RequestBody.create(MediaType.parse("text/plain"), nameStr);
RequestBody avatarPart = RequestBody.create(MediaType.parse("image/jpeg"), avatarFile);
api.addUser(namePart, avatarPart); 

3. Content-Type: application/jsonIndicates submitting data in json format

The format is as follows:

POST /users HTTP/1.1
Host: app.test.com
Content-Type: application/json; charset=utf-8 
Content-Length: 38

{
    
    "name":"zhangsan","gender":"male"} 

Corresponding Retrofit code:

@POST("/users")
Call<User> addUser(@Body("user") User user); 
...
// 需要使用 JSON 相关的 Converter
api.addUser(user); 

JSON is returned in the response:

HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8 
Content-length: 234

[{
    
    "login":"mojombo","id":1,"node_id":"MDQ6VXN1 cjE=",
"avatar_url":"https://avatars0.githubuse rcontent.com/u/1?v=4",
"gravat":....}]

4. Content-Type: image/jpegIndicates submitting binary file content and uploading a single file

The format is as follows:

POST /user/1/avatar HTTP/1.1 
Host: app.test.com
Content-Type: image/jpeg 
Content-Length: 1575 

JFIFHH9......

Corresponding Retrofit code:

@POST("users/{id}/avatar")
Call<User> updateAvatar(@Path("id") String id, @Body RequestBody avatar);
...
RequestBody avatarBody = RequestBody.create(MediaType.parse("image/jpeg"), avatarFile);
api.updateAvatar(id, avatarBody)

Binary content is returned in the response:

HTTP/1.1 200 OK
Content-type: image/jpeg 
Content-length: 1575 

JFIFHH9......

Content-Type type/MIME type acquisition

Common body data types mainly include the following four categories:

  • text: Readable data in text format, such as text/htmlhypertext, text/plainplain text, text/cssstyle sheet, etc.

  • image: Image files, such as image/gif, image/jpeg, image/pngetc.

  • audio/video: Audio and video data, such as audio/mpeg, video/mp4etc.

  • application: The format is not fixed and can be text or binary. It must be interpreted by the upper-layer application. Common ones include application/json, application/javascript, application/pdfetc.

  • If you don’t know what type the data is, use application/octet-streamopaque binary data.

For a complete type comparison table, please refer to the MIME type list maintained by IANA: https://www.iana.org/assignments/media-types/media-types.xhtml

In fact, we don't need to remember these. In the development language used, there are many system built-in methods or third-party libraries that can directly output the MIME type according to the file.

In Android, there are two built-in methods to obtain the MIME type of a file

  1. MimeTypeMapGet it via
  2. ContentResolverGet it via

Here is sample code to use MimeTypeMapto Fileget the MIME type of an object:

import android.webkit.MimeTypeMap;

public String getMimeType(File file) {
    
    
    String mimeType = null;
    String extension = MimeTypeMap.getFileExtensionFromUrl(file.getAbsolutePath());

    if (extension != null) {
    
    
        mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase());
    }

    return mimeType;
}

This method is first used MimeTypeMap.getFileExtensionFromUrl()to get the file extension, and then used MimeTypeMap.getSingleton().getMimeTypeFromExtension()to get the corresponding MIME type. Finally, it returns the MIME type string found.

Note that this method relies on the file extension to determine the MIME type, so the file's extension must be set correctly. If the file has no extension or an incorrect extension, this method may not correctly identify the MIME type.

But sometimes what we get during development is a Content Uri object (for example) queried from the system media database content://media/external/images/media/94. It does not have a file extension. How to get its MIME type?

You can consider using it at this time ContentResolver. The following is ContentResolverthe reference code for using to obtain Content Uri:

import android.content.ContentResolver;
import android.content.Context;
import android.net.Uri;

public String getMimeTypeFromContentUri(Context context, Uri contentUri) {
    
    
    ContentResolver contentResolver = context.getContentResolver();
    String mimeType = contentResolver.getType(contentUri);
    return mimeType;
}

Another situation is that we have a Filetype Uri(that filestarts with, such as file://xxx/xx) that can be obtained through the following reference code:

String fileExtension = MimeTypeMap.getFileExtensionFromUrl(fileUri.toString());
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension.toLowerCase());

The following reference code can be applied to both Content Uri and File Uri situations:

public String getMimeType(Context context, Uri uri) {
    
    
    String mimeType = null;
    if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
    
    
        ContentResolver cr = context.getContentResolver();
        mimeType = cr.getType(uri);
    } else {
    
    
        String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri.toString());
        mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension.toLowerCase());
    }
    return mimeType;
}

Guess you like

Origin blog.csdn.net/lyabc123456/article/details/133324240