詳解http post請求的幾種數據傳輸方式

在Http請求裏post是其中比較常用的提交數據的請求方式,那麼接下來就給大家詳細講解下post的幾種數據傳輸格式,以及寫法。

Http的請求傳輸方式很多:

我們着重講解Post方式。Post請求包含兩部分:請求頭(header)和請求體(body)。

Post常見的請求體(body)有三種傳輸內容類型Content-type:application/x-www-form-urlencoded、application/json、multipart/form-data,當然還有其他的幾種,不過不常用,常用的就是這三種。

先看第一種:application/x-www-form-urlencoded。

通過Postman可以看到Post請求的參數一般放在Body裏。我們的application/x-www-form-urlencoded方式也是Post請求最早支持的一種數據傳輸方式,這種也是key和value形式,將我們的參數類似於GET方式那樣拼接成一個字符串,例如:key1=value1&key2=value2,這種形式,然後將這個參數字符串進行urlencode編碼,放到Body裏進行發送請求數據。

接下來分別用Java Spring MVC、Android OkHttp、Retrofit、JS Ajax、Nodejs分別演示下這種方式的請求和接口編寫:

在Java的Spring MVC中默認的編寫Controller接口請求數據傳輸就是這種方式:application/x-www-form-urlencoded。

package com.web.mvc.controller;

import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.web.mvc.model.Entity;
import com.web.mvc.model.User;
import com.web.mvc.service.EntityService;
import com.web.mvc.service.IEntityService;
import com.web.mvc.utils.RedisUtils;
import com.web.mvc.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

import org.apache.commons.codec.binary.Base64;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

//@Controller
@RestController
@RequestMapping("/entity")
public class EntityController {
    @Autowired
    private IEntityService entityService;

    //默認form-urlcoded
    @CrossOrigin
    @RequestMapping(value = "/urlcodedReq", method = RequestMethod.POST)
    @ResponseBody
    public String urlcodedReq(@RequestParam String name,
                              @RequestParam String pwd) {
        System.out.println("urlcodedReq:" + name + "  " + pwd);
        Gson gson = new Gson();
        HashMap<String, String> map = new HashMap<>();
        map.put("name", name);
        map.put("pwd", pwd);
        return gson.toJson(map);
    }
}

@CrossOrigin:用來處理支持跨域請求的;

@ResponseBody:作用在方法上,表示請求返回的數據寫入http response body裏,也就是返回數據,而不是進行頁面跳轉。

以上就是Java Spring MVC編寫Controller Post接口的寫法。

接下來看下Android中Retrofit的請求寫法:

public interface ApiService {

    //application/x-www-form-urlencoded
    @FormUrlEncoded
    @POST("urlcodedReq")
    Call<ResponseBody> getRepos(@Field("name") String name, @Field("pwd") String pwd);
}

就是加入了@FormUrlEncoded註解即可。

再看下Okhttp發送請求的寫法:

public class Utils {
    private static String
            url = "http://192.168.1.130:8086/entity/urlcodedReq";

    public static void okPost() {
        OkHttpClient client = new OkHttpClient();
        client.newBuilder()
                .build();
        //application/x-www-form-urlencoded
        RequestBody body = new FormBody.Builder()
                .add("name", "123")
                .add("pwd", "pwd1")
                .build();

        Request request = new Request.Builder()
                .post(body)
                .url(url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("onFailure:" + e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("onResponse:" + response.body().string());
            }
        });
    }
}

接下來看下JS中Ajax的寫法:

/**
 * 原生Ajax POST請求
 */
function getOrigantAjaxPost() {
    var stringData='name=value1&pwd=value2'
    var oAjax = null;
    //這裏進行HTTP請求
    try {
        oAjax = new XMLHttpRequest();
    } catch (e) {
        oAjax = new ActiveXObject("Microsoft.XMLHTTP");
    };
    //post方式
    oAjax.open('post', 'http://' + hostName + ':' + port + '/entity/urlReq', true);
    oAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    //post發送數據
    oAjax.send(stringData);
    oAjax.onreadystatechange = function () {
        //當狀態爲4的時候,執行以下操作
        if (oAjax.readyState == 4 && oAjax.status == 200) {
            try {
                //+ oAjax.responseText
                console.log('data:' + oAjax.responseText);
            } catch (e) {
                // alert('你訪問的頁面出錯了' + e);
            };
        };
    };
}

Jquery Ajax寫法:

function getOrigantAjaxPost() {
    var stringData = 'name=value1&pwd=value2'
    $.ajax({
        data: stringData,
        async: true,
        url: 'http://' + hostName + ':' + port + '/entity/urlReq',
        type: "post",
        processData: false,  //tell jQuery not to process the data
        contentType: "application/x-www-form-urlencoded",
        success: function (data, status) {
            // alert("Data: " + status);
            console.log("Data: " + JSON.stringify(data) + "  " + status);
        },
        error: function (e) {
            // alert("Data: error" + JSON.stringify(e));
            console.log('error ' + JSON.stringify(e));
        }
    });
}

接下來再看下Nodejs的接口和請求寫法:

var http = require("http");
var url = require('url');
var express = require('express')
var bodyParser = require('body-parser');
//設置主機名
var hostName = '192.168.56.1';
//設置端口
var port = 8092;
var app = express()
var urlencodedParser = bodyParser.urlencoded({ extended: false })
routes.post('/url', urlencodedParser, (req, res) => {
    //解析參數
    var params = req.body;
    var user = {};
    user.name = params.name;
    user.pwd = params.pwd;
    var response = { status: 1, data: user };
    res.send(JSON.stringify(response));
    res.end();
});

Nodejs原生寫Post接口解析寫法:

const http = require('http');

//用http模塊創建一個http服務端 
http.createServer(function(req, res) {
  if (req.method.toLowerCase() === 'post') {
    var body = '';   
    req.on('data', function(chunk){
      body += chunk;
    });

    req.on('end', function(){
      if(req.headers['content-type'].indexOf('application/json')!==-1){
        // JSON 格式請求體解析
        JSON.parse(body);
      } else if(req.headers['content-type'].indexOf('application/octet-stream')!==-1){
        // Raw 格式請求體解析
        // ……
      } else if(req.headers['content-type'].indexOf('text/plain')!==-1){
        // text 文本格式請求體解析
        // ……
      } else if(req.headers['content-type'].indexOf('application/x-www-form-urlencoded')!==-1){
        // URL-encoded 格式請求體解析
        // ……
      } else {
      	// 其它格式解析
      }
    })
  } else {
    res.end('其它提交方式');
  }
}).listen(3000);

Nodejs的請求寫法:

/**
 * 原生POST請求
 */
function urlPost() {
    var http = require('http');
    var querystring = require('querystring');
    var contents = querystring.stringify({
        name: 'nameuser',
        pwd: '123'
    });
    var options = {
        host: hostName,
        port: port,
        path: '/entity/req',
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': contents.length
        }
    }
    var req = http.request(options, function (res) {
        res.setEncoding('utf8');
        res.on('data', function (data) {
            console.log("data:", data);//返回數據
        });
    });
    req.write(contents);
    req.end();
}

再看第二種:application/json。

application/json也就是告訴我們的服務器我們的消息體內容類型是序列化的JSON字符串,例如:{ "name": "value1", "pwd": "value2" }。獲取到這個body直接解析Json格式字符串即可拿到參數數據。

接下來分別用Java Spring MVC、Android OkHttp、Retrofit、JS Ajax、Nodejs分別演示下這種方式的請求和接口編寫:

在Java的Spring MVC中編寫Controller接口接收解析application/json這種數據格式的需要在註解裏定義consumes和produces爲application/json類型。

@CrossOrigin
    @RequestMapping(value = "/req", method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_VALUE
            , produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String postReq(@RequestBody User user) {
        System.out.println("req:" + user.getName() + "  " + user.getPwd());
        Gson gson = new Gson();
        HashMap<String, String> map = new HashMap<>();
        map.put("name", user.getName());
        map.put("pwd", user.getPwd());
        return gson.toJson(map);
    }

Retrofit定義的話就是要加上@Headers註解,裏面聲明Content-Type即可。

//application/json
    @Headers({"Content-Type: application/json", "Accept: application/json"})
    @POST("req")
    Call<ResponseBody> getRepos(@Body Entity entity);

Android OkHttp使用方法如下:

public static void okPost() {
        OkHttpClient client = new OkHttpClient();
        client.newBuilder()
                .build();
        //application/json
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        Gson gson = new Gson();
        HashMap<String, String> map = new HashMap<>();
        map.put("name", "name1");
        map.put("pwd", "pwd1");
        String postString = gson.toJson(map);
        RequestBody requestBody = RequestBody.create(mediaType, postString);
        
        Request request = new Request.Builder()
                .post(requestBody)
                .url(url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("onFailure:" + e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("onResponse:" + response.body().string());
            }
        });
    }

Ajax寫法:

/**
 * 原生Ajax POST請求
 */
function getOrigantAjaxPost() {
    var postData = '{ "name": "value1", "pwd": "value2" }';
    var oAjax = null;
    //這裏進行HTTP請求
    try {
        oAjax = new XMLHttpRequest();
    } catch (e) {
        oAjax = new ActiveXObject("Microsoft.XMLHTTP");
    };
    //post方式
    oAjax.open('post', 'http://' + hostName + ':' + port + '/entity/req', true);
    oAjax.setRequestHeader("Content-type", "application/json");
    //post發送數據
    oAjax.send(postData);
    oAjax.onreadystatechange = function () {
        //當狀態爲4的時候,執行以下操作
        if (oAjax.readyState == 4 && oAjax.status == 200) {
            try {
                //+ oAjax.responseText
                console.log('tryForm:' + oAjax.responseText);
                // alert('readyState' + oAjax.status + "  "
                //     + oAjax.responseText);
            } catch (e) {
                // alert('你訪問的頁面出錯了' + e);
            };
        };
    };
}

Jquery Ajax寫法:

/**
 * 原生Ajax POST請求
 */
function getOrigantAjaxPost() {
    var postData = '{ "name": "value1", "pwd": "value2" }';
    $.ajax({
        data: postData,
        async: true,
        url: 'http://' + hostName + ':' + port + '/entity/req',
        type: "post",
        processData: false,  //tell jQuery not to process the data
        contentType: "application/json",  //tell jQuery not to set contentType
        success: function (data, status) {
            // alert("Data: " + status);
            console.log("Data: " + JSON.stringify(data) + "  " + status);
        },
        error: function (e) {
            // alert("Data: error" + JSON.stringify(e));
            console.log('error ' + JSON.stringify(e));
        }
    });
}

Nodejs的接口寫法,只是變成bodyParser.json即可:

var urlencodedParser = bodyParser.json({ extended: false })
routes.post('/url', urlencodedParser, (req, res) => {
    //解析參數
    var params = req.body;
    var user = {};
    user.name = params.name;
    user.pwd = params.pwd;
    var response = { status: 1, data: user };
    res.send(JSON.stringify(response));
    res.end();
});

Nodejs請求的寫法:

/**
 * 原生POST請求
 */
function getAPost() {
    var http = require('http');
    var contents='{ "name": "value1json", "pwd": "value2" }';
    var options = {
        host: hostName,
        port: port,
        path: '/entity/req',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': contents.length
        }
    }
    var req = http.request(options, function (res) {
        res.setEncoding('utf8');
        res.on('data', function (data) {
            console.log("data:", data);//返回數據
        });
    });
    req.write(contents);
    req.end();
}

接下來看下最後一種常用的Post請求的數據格式,:multipart/form-data。

這種格式主要用來進行文件上傳,當然可以作爲表單內容進行鍵值對提交數據,各個表單項之間用boundary分開。

接下來分別用Java Spring MVC、Android OkHttp、Retrofit、JS Ajax、Nodejs分別演示下這種方式的請求和接口編寫:

在Java的Spring MVC中編寫Controller接口接收解析multipart/form-data這種數據格式的需要在註解裏定義consumes和produces爲multipart/form-data​​​​​​​類型。

@CrossOrigin
    @RequestMapping(value = "/upReq", method = RequestMethod.POST,
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public String uploadReq(@RequestPart(value = "file") MultipartFile multipartFile,
                            @RequestParam("description") String description) {
        String fileType = multipartFile.getContentType();
        String fileName = multipartFile.getOriginalFilename();
        File file = new File("E:/file.jpg");
        System.out.println("請求:" + fileType + " "
                + fileName + "  " + description);
        try {
            multipartFile.transferTo(file);
            return "success";
        } catch (IOException e) {
            e.printStackTrace();
            return "failure";
        }
    }

    @CrossOrigin
    @RequestMapping(value = "/formReq", method = RequestMethod.POST,
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public String formDataReq(@RequestParam String name,
                              @RequestParam String pwd) {
        System.out.println("formReq:" + name + "  " + pwd);
        Gson gson = new Gson();
        HashMap<String, String> map = new HashMap<>();
        map.put("name", name);
        map.put("pwd", pwd);
        return gson.toJson(map);
    }

Retrofit的寫法就是加上@Multipart註解,參數用@Part進行註解:

    //multipart/form-data
    @Multipart
    @POST("req")
    Call<ResponseBody> getRepos(@Part("description") RequestBody description,
                                @Part MultipartBody.Part file);

Android OkHttp的寫法是:

public static void okPost() {
        OkHttpClient client = new OkHttpClient();
        client.newBuilder()
                .build();

        //multipart/form-data
        File file = new File("E:/img.png");
        RequestBody fileBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(),
                        RequestBody.create(MediaType.parse("image/png"), file))
                .addFormDataPart("description", "description")
                .build();

        Request request = new Request.Builder()
                .post(fileBody)
                .url(formUrl)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("onFailure:" + e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("onResponse:" + response.body().string());
            }
        });
    }

Ajax寫法是:

/**
 * 原生Ajax POST請求
 */
function getOrigantAjaxPost() {
    var oAjax = null;
    //這裏進行HTTP請求
    try {
        oAjax = new XMLHttpRequest();
    } catch (e) {
        oAjax = new ActiveXObject("Microsoft.XMLHTTP");
    };
    var formData = new FormData();
    formData .append("file", file); // 文件對象
    formData .append("description", "description");
    //post方式
    oAjax.open('post', 'http://' + hostName + ':' + port + '/entity/formReq', true);
    // oAjax.setRequestHeader("Content-type", "multipart/form-data");
    //post發送數據
    oAjax.send(formData );
    oAjax.onreadystatechange = function () {
        //當狀態爲4的時候,執行以下操作
        if (oAjax.readyState == 4 && oAjax.status == 200) {
            try {
                //+ oAjax.responseText
                console.log('tryForm:' + oAjax.responseText);
                // alert('readyState' + oAjax.status + "  "
                //     + oAjax.responseText);
            } catch (e) {
                // alert('你訪問的頁面出錯了' + e);
            };
        };
    };
}

Jquery Ajax寫法:

/**
 * 原生Ajax POST請求
 */
function getOrigantAjaxPost() {
    var form = new FormData();
    form.append("file", file); // 文件對象
    form.append("description", "image");
    $.ajax({
        data: form,
        async: true,
        url: 'http://' + hostName + ':' + port + '/entity/formReq',
        type: "post",
        processData: false,  //tell jQuery not to process the data
        contentType: "multipart/form-data",  //tell jQuery not to set contentType
        success: function (data, status) {
            // alert("Data: " + status);
            console.log("Data: " + data + "  " + status);
        },
        error: function (e) {
            // alert("Data: error" + JSON.stringify(e));
            console.log('error ' + JSON.stringify(e));
        }
    });
}

Nodejs接口寫法,用了multipart:

var multipartMiddleware = multipart();
routes.post('/url', multipartMiddleware, (req, res) => {
    res.send("success:" + JSON.stringify(req.body) + " " + req.files.file.type);
    res.end();
});

Nodejs請求寫法:

/**
 * 原生POST請求
 */
function getAPost() {
    var http = require('http');
    var formData = new FormData();
    formData.append('file', fs.createReadStream("./filename.zip"));
    formData.append('description', 'image');
    var options = {
        host: hostName,
        port: port,
        path: '/entity/req',
        method: 'POST',
        headers: {
            'Content-Type': 'multipart/form-data',
        }
    }
    var req = http.request(options, function (res) {
        res.setEncoding('utf8');
        res.on('data', function (data) {
            console.log("data:", data);//返回數據
        });
    });
    req.write(formData);
    req.end();
}

以上就是給大家介紹的主流Http Post的數據傳輸格式在各個語言上的用法。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章