postman模拟post请求的几种请求体

postman的几种参数格式
post类型的body中可以存放任意的内容格式,浏览器可以根据请求头中指定的content-type类型对请求体进行解析。下面介绍postman如何对四种典型的请求体进行模拟。

  1. form-data
    即multipart/form-data,它将表单的数据组织成Key-Value形式,用分隔符boundary(boundary可任意设置)处理成一条消息。
    由于有boundary隔离,所以既可以上传文件,也可以上传参数。
POST  HTTP/1.1
Host: test.app.com
Cache-Control: no-cache
Postman-Token: 59227787-c438-361d-fbe1-75feeb78047e
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="filekey"; filename=""
Content-Type: 


------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="textkey"

tttttt
------WebKitFormBoundary7MA4YWxkTrZu0gW--

请求体中的boundary参数指定的就是分隔体,可以看到请求内容被分为了两段,第一段对应filekey,第二段对应textkey。

  1. x-www-form-urlencoded
    即application/x-www-from-urlencoded,将表单内的数据转换为Key-Value。
POST  HTTP/1.1
Host: test.app.com
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Postman-Token: e00dbaf5-15e8-3667-6fc5-48ee3cc89758

key1=value1&key2=value2

  1. raw
    可以上传任意格式的【文本】,可以上传text、json、xml、html等
POST  HTTP/1.1
Host: test.app.com
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 05a064d2-fa79-10c0-caba-15ca5d1a940f

{"key1":"value1","key2":"value2"}

  1. binary
    即Content-Type:application/octet-stream,只可以上传二进制数据,通常用来上传文件。由于没有键值,所以一次只能上传一个文件。
POST  HTTP/1.1
Host: test.app.com
Cache-Control: no-cache
Postman-Token: 5ad66f08-6faa-aba0-744a-ca958b1a0fc2

undefined

注意:

multipart/form-data与x-www-form-urlencoded区别:html中的form
表单有两种:application/x-www-form-urlencoded和multipart/form-data。application/x-www-form-urlencoded是默认的MIME内容编码类型,它在传输比较大的二进制或者文本数据时效率极低。

MIME:

简单说,MIME类型就是设定某种扩展名的文件用一种应用程序来打开的方式类型。服务器会将它们发送的多媒体数据的类型告诉浏览器,而通知手段就是说明该多媒体数据的MIME类型,服务器将
MIME标志符放入传送的数据中来告诉浏览器使用哪种插件读取相关文件。

  1. multipart/form-data:
    既可以上传文件等二进制数据,也可以上传表单键值对,只是最后会转化为一条信息。当设置multipart/form-data,http会忽略contentType 属性。

  2. x-www-form-urlencoded:只能上传键值对,不能用于文件上传。不同的field是用&区分开的。这两个类均实现了HttpEntity接口,使用如下:

public static String testUpload(String url) {
        String result = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(url);
        try {
            FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
            StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
            HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment)
                    .build();
            httppost.setEntity(reqEntity);
            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                    result = EntityUtils.toString(response.getEntity(), "UTF-8");
                }
            } finally {
                response.close();
                httpclient.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String testParam(String url) {
        String result = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        httpclient = HttpsHelper.newHttpsCloseableClient();
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("key1", "value1"));
        params.add(new BasicNameValuePair("key2", "value2"));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            httpPost.setConfig(requestConfig);
            CloseableHttpResponse httpResp = httpclient.execute(httpPost);
            try {
                int statusCode = httpResp.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                    result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
                }
            } finally {
                httpResp.close();
                httpclient.close();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java中的HttpURLConnection类来模拟Postman发送POST请求。具步骤如下: 1. 创建URL对象,指定请求的URL地址。 2. 调用URL对象的openConnection()方法,获取HttpURLConnection对象。 3. 设置请求的方法为POST,调用setRequestMethod()方法。 4. 设置请求头,调用setRequestProperty()方法。 5. 设置请求,调用getOutputStream()方法获取输出,将请求参数写入输出。 6. 发送请求,调用connect()方法。 7. 获取响应,调用getInputStream()方法获取输入,读取响应数据。 8. 关闭连接,调用disconnect()方法。 示例代码如下: ``` import java.io.*; import java.net.*; public class PostRequestDemo { public static void main(String[] args) throws Exception { String url = "http://example.com/api"; String params = "param1=value1&param2=value2"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 设置请求方法为POST con.setRequestMethod("POST"); // 设置请求头 con.setRequestProperty("User-Agent", "Mozilla/5."); con.setRequestProperty("Accept-Language", "en-US,en;q=.5"); // 设置请求 con.setDoOutput(true); OutputStream os = con.getOutputStream(); os.write(params.getBytes()); os.flush(); os.close(); // 发送请求 con.connect(); // 获取响应 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 输出响应结果 System.out.println(response.toString()); // 关闭连接 con.disconnect(); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值